findymail-mcp 0.1.19 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -16,12 +16,27 @@ This MCP server exposes the following tools:
16
16
  | `reverse_email_lookup` | Find person info from an email |
17
17
  | `lookalike_search` | Find similar companies from a seed domain using vector similarity |
18
18
  | `generate_lead_list` | AI-powered company discovery from a natural language description of your ideal customer |
19
- | `get_lead_list_results` | Retrieve results from a previously generated lead list |
19
+ | `get_lead_list_results` | Follow a lead list run and read its results one page at a time (or check its status once with `wait: false`) |
20
+ | `get_credit_balance` | Check the finder and verifier credits left before starting a paid run |
21
+ | `get_credit_usage` | Report credits spent over a date range, for you or (team owner only) per team member |
20
22
  | `list_exclusion_lists` | List the exclusion lists you own or that are shared with your team |
21
23
  | `create_exclusion_list` | Create a new exclusion list |
22
24
  | `list_exclusion_domains` | List the domains held by an exclusion list, with their ids |
23
25
  | `add_exclusion_domains` | Add domains to an exclusion list (or to your global exclusions) |
24
26
  | `remove_exclusion_domains` | Remove domains from an exclusion list, by domain id |
27
+ | `search_technologies` | Search the technology catalog by name (free) |
28
+ | `get_company_technologies` | Get a company's technology stack from its domain |
29
+ | `list_contact_lists` | List the contact lists you own or that are shared with your team |
30
+ | `create_contact_list` | Create a new contact list |
31
+ | `update_contact_list` | Rename a contact list or change its team sharing |
32
+ | `delete_contact_list` | Delete a contact list (irreversible; the contacts stay saved) |
33
+ | `list_contacts` | Read saved contacts back, from one list or all of them, one page at a time |
34
+ | `list_signals` | List the buying signals your monitors detected, with filters |
35
+ | `get_signal` | Read one signal |
36
+ | `list_monitors` | List your signal monitors and your team's shared ones |
37
+ | `create_monitor` | Create a signal monitor (charges credits for every signal it delivers) |
38
+ | `update_monitor` | Change a monitor's settings |
39
+ | `delete_monitor` | Delete a signal monitor (irreversible) |
25
40
 
26
41
  ### Exclusion lists
27
42
 
@@ -168,6 +183,9 @@ Once configured, you can ask your AI assistant:
168
183
  - "Find me 10 marketing managers at SaaS companies in San Francisco"
169
184
  - "Find companies similar to stripe.com in the same country"
170
185
  - "Create an exclusion list called Competitors and add stripe.com and brex.com to it"
186
+ - "How many credits do I have left? Is that enough for 2,000 companies with a CTO each?"
187
+ - "Which of these 20 accounts use HubSpot?"
188
+ - "Watch for new VP Sales hires at fintechs in France and save them to my Fintech list"
171
189
  - "Find 50 fintech companies in Europe, excluding my Competitors list, and add the results to it so I don't get them again"
172
190
 
173
191
  ## API Key
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "findymail-mcp",
3
- "version": "0.1.19",
3
+ "version": "0.2.0",
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",
package/src/api.js CHANGED
@@ -245,7 +245,10 @@ async function request(method, endpoint, { apiKey, body, timeoutMs = API_TIMEOUT
245
245
  throw error;
246
246
  }
247
247
 
248
- const data = await response.json();
248
+ // A delete answers 204, or 200 with an empty body: that is a success, not
249
+ // a JSON parse error.
250
+ const raw = await response.text();
251
+ const data = raw.trim() === "" ? {} : JSON.parse(raw);
249
252
  log(`API ${method} ${path} → ${response.status} in ${elapsed()}`);
250
253
  return data;
251
254
  } catch (error) {
@@ -275,6 +278,20 @@ export function apiGet(endpoint, apiKey, options = {}) {
275
278
  return request("GET", endpoint, { ...options, apiKey });
276
279
  }
277
280
 
281
+ /**
282
+ * Make authenticated PUT request to Findymail API
283
+ */
284
+ export function apiPut(endpoint, body = {}, apiKey, options = {}) {
285
+ return request("PUT", endpoint, { ...options, apiKey, body });
286
+ }
287
+
288
+ /**
289
+ * Make authenticated PATCH request to Findymail API
290
+ */
291
+ export function apiPatch(endpoint, body = {}, apiKey, options = {}) {
292
+ return request("PATCH", endpoint, { ...options, apiKey, body });
293
+ }
294
+
278
295
  /**
279
296
  * Make authenticated DELETE request to Findymail API
280
297
  */
package/src/tools.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod";
2
- import { log, apiPost, apiGet, apiDelete, resolveApiKey, formatResponse, formatError } from "./api.js";
2
+ import { log, apiPost, apiGet, apiPut, apiPatch, apiDelete, resolveApiKey, formatResponse, formatError } from "./api.js";
3
3
 
4
4
  // Every tool reaches the Findymail API over the network, so `openWorldHint` is
5
5
  // true throughout. The lookups below are marked `readOnlyHint: false` even
@@ -15,6 +15,56 @@ const LOOKUP = { readOnlyHint: false, destructiveHint: false, idempotentHint: tr
15
15
  // whatever each upstream call does, leaving room for the network and the reply.
16
16
  const LEAD_LIST_BUDGET_MS = 50 * 1000;
17
17
  const POLL_INTERVAL_MS = 3000;
18
+ // The API's own default and cap for a page of lead list results.
19
+ const DEFAULT_RESULTS_PER_PAGE = 100;
20
+ const MAX_RESULTS_PER_PAGE = 500;
21
+
22
+ // The API takes either one flat list or up to 3 priority tiers, and refuses a
23
+ // mix of the two shapes with a 422 — so does the schema, before any credit is
24
+ // spent.
25
+ const MAX_JOB_TITLE_TIERS = 3;
26
+ const JOB_TITLE_TIERS = z.array(z.array(z.string()).min(1)).min(1).max(MAX_JOB_TITLE_TIERS);
27
+
28
+ // YYYY-MM-DD, the only format the usage reports document. A function, not a
29
+ // shared instance: the JSON Schema generator turns a reused instance into a
30
+ // $ref to the first field, which some clients do not resolve.
31
+ const reportDate = () => z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Use the YYYY-MM-DD format");
32
+
33
+ // Monitor types the API accepts, and what a delivered signal costs at least.
34
+ const SIGNAL_TYPES = ["keyword_mention", "post_engagement", "new_hire", "job_change", "company_hiring"];
35
+ const SIGNAL_BASE_COST = 1;
36
+ const MAX_MONITOR_MATCHES = 10000;
37
+
38
+ // Fields create_monitor and update_monitor share. The per-type rules (what is
39
+ // required, what is forbidden) stay with the API, which names them in its 422.
40
+ const MONITOR_FIELDS = {
41
+ name: z.string().trim().min(1).max(255).describe("Monitor name (max 255 characters)"),
42
+ keywords: z.array(z.string().max(100)).max(5).optional().describe("Keywords to watch for (max 5, each max 100 characters). Required for keyword_mention, and for post_engagement without post_url or profile_url."),
43
+ engagement_types: z.array(z.enum(["like", "comment"])).min(1).optional().describe("post_engagement only (required there): which engagements to catch"),
44
+ target_companies: z.array(z.string()).max(100).optional().describe("new_hire and job_change only: company names or domains to watch (max 100). Without it, icp_filters is required."),
45
+ job_offer_title_keywords: z.array(z.string()).max(10).optional().describe("company_hiring only (required there): job offer title keywords, substring match, any of them (max 10)"),
46
+ icp_filters: z.object({
47
+ industries: z.array(z.string()).optional().describe("LinkedIn industry names (Industry Codes V2), e.g. [\"Biotechnology\"]"),
48
+ employee_count_ranges: z.array(z.enum(["1-10", "11-50", "51-200", "201-500", "501-1000", "1001-5000", "5001-10000", "10001+"])).optional(),
49
+ countries: z.array(z.string().length(2)).optional().describe("ISO 3166-1 alpha-2 country codes, e.g. [\"US\", \"FR\"]"),
50
+ job_title_keywords: z.array(z.string()).max(10).optional().describe("Contact job title keywords (max 10). Not for company_hiring."),
51
+ seniority_levels: z.array(z.number().int()).optional().describe("1=Entry, 4=IC, 6=Senior IC, 8=Management, 9=Director, 11=VP, 13=Executive, 14=C-Suite, 15=Founder. Not for company_hiring."),
52
+ }).optional().describe("Narrow the matches to an ideal customer profile. Company-level filters (industries, sizes, countries) and contact-level ones (job titles, seniority) each add 1 credit per signal on keyword_mention and post_engagement."),
53
+ enrichment_level: z.enum(["none", "email", "email_phone"]).optional().describe("What to look up for each matched contact. Must be \"none\" for company_hiring."),
54
+ lead_list_id: z.number().int().positive().optional().describe("Contact list to save every matched contact into, from `list_contact_lists`"),
55
+ webhook_url: z.string().url().startsWith("https://").max(2048).optional().describe("HTTPS URL to notify on each new signal"),
56
+ ai_relevance_prompt: z.string().max(500).optional().describe("What makes a signal relevant to the user (max 500 characters); each signal then gets a 0-5 relevance score"),
57
+ is_shared: z.boolean().optional().describe("Share the monitor with your current team"),
58
+ };
59
+
60
+ // A large company's stack runs to hundreds of technologies (293 for stripe.com,
61
+ // 58 KB): cut it down before it reaches the agent's context.
62
+ const DEFAULT_TECHNOLOGIES_LIMIT = 50;
63
+ const MAX_TECHNOLOGIES_LIMIT = 500;
64
+
65
+ // list_contacts pages through the saved contacts; the API itself sets no cap.
66
+ const DEFAULT_CONTACTS_PER_PAGE = 25;
67
+ const MAX_CONTACTS_PER_PAGE = 100;
18
68
 
19
69
  // `title` became a top-level field on Tool in the 2025-06-18 spec, but clients
20
70
  // and review tooling written against the earlier shape still read it out of
@@ -37,23 +87,26 @@ export function registerTools(server, { leadListBudgetMs = LEAD_LIST_BUDGET_MS }
37
87
  "find_email",
38
88
  toolConfig({
39
89
  title: "Find Email",
40
- description: "Find a verified B2B email address for one person. Identify them either by full name plus company domain, or by LinkedIn profile URL — one of those two combinations is required, and the LinkedIn URL takes precedence when both are supplied. Returns the contact with the email address, the person's name and the company domain. Addresses are verified before being returned, so a person whose address cannot be verified comes back as not found rather than as a guess. Use it when you need one specific person's email, and chain it after `find_employees` (passing the returned name + domain, or the returned LinkedIn URL) to put emails on a list of contacts. Costs 1 finder credit per email found; a lookup that finds nothing is not charged.",
90
+ description: "Find a verified B2B email address for one person. Identify them either by full name plus company domain, or by LinkedIn profile URL — one of those two combinations is required, and the LinkedIn URL takes precedence when both are supplied. Returns the contact with the email address, the person's name and the company domain. Addresses are verified before being returned, so a person whose address cannot be verified comes back as not found rather than as a guess. Use it when you need one specific person's email, and chain it after `find_employees` (passing the returned name + domain, or the returned LinkedIn URL) to put emails on a list of contacts. Set list_id to also save the contact found into one of your contact lists (see `list_contact_lists`). Costs 1 finder credit per email found; a lookup that finds nothing is not charged.",
41
91
  inputSchema: {
42
92
  name: z.string().optional().describe("Person's full name (required with domain)"),
43
93
  domain: z.string().optional().describe("Company domain (required with name)"),
44
94
  linkedin_url: z.string().optional().describe("LinkedIn profile URL (alternative to name+domain)"),
95
+ list_id: z.number().int().positive().optional().describe("Contact list to save the contact found into, from `list_contact_lists` or `create_contact_list`. Omit to save it to your contacts only."),
45
96
  },
46
97
  annotations: LOOKUP,
47
98
  }),
48
99
  async (params, extra) => {
49
- log(`find_email: by ${params.linkedin_url ? "linkedin_url" : "name+domain"}`);
100
+ log(`find_email: by ${params.linkedin_url ? "linkedin_url" : "name+domain"} list=${params.list_id ? "set" : "none"}`);
50
101
 
51
102
  try {
52
103
  const apiKey = resolveApiKey(extra);
104
+ const list = params.list_id === undefined ? {} : { list: params.list_id };
53
105
 
54
106
  if (params.linkedin_url) {
55
107
  const data = await apiPost("/search/linkedin", {
56
108
  linkedin_url: params.linkedin_url,
109
+ ...list,
57
110
  }, apiKey);
58
111
  return formatResponse(data);
59
112
  }
@@ -62,6 +115,7 @@ export function registerTools(server, { leadListBudgetMs = LEAD_LIST_BUDGET_MS }
62
115
  const data = await apiPost("/search/name", {
63
116
  name: params.name,
64
117
  domain: params.domain,
118
+ ...list,
65
119
  }, apiKey);
66
120
  return formatResponse(data);
67
121
  }
@@ -283,7 +337,7 @@ export function registerTools(server, { leadListBudgetMs = LEAD_LIST_BUDGET_MS }
283
337
  limit: z.number().int().min(1).max(5000).optional().default(100).describe("Maximum number of results (default: 100, max: 5000)"),
284
338
  mode: z.enum(["broad", "targeted"]).optional().default("broad").describe("'broad' = fast export (1 credit/10 companies), 'targeted' = AI-qualified results (1 credit/company)"),
285
339
  find_contact: z.boolean().optional().default(true).describe("Search for contacts at each company (+1 credit/contact found)"),
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'])"),
340
+ target_job_titles: z.union([z.array(z.string()), JOB_TITLE_TIERS]).optional().default(["CEO"]).describe(`Job titles to target when find_contact is true. Either one flat list, where every title has the same priority (e.g. ['CEO', 'CTO']), or up to ${MAX_JOB_TITLE_TIERS} priority tiers, each a non-empty list: the contact is searched with the first tier and the next tier is only tried at companies where nothing matched (e.g. [['CTO'], ['VP Engineering', 'Head of Engineering'], ['CEO']]). Never mix the two shapes in one list.`),
287
341
  find_email: z.boolean().optional().default(true).describe("Enrich contacts with email (+1 credit/email found). Requires find_contact: true"),
288
342
  find_phone: z.boolean().optional().default(false).describe("Enrich contacts with phone (+10 credits/phone found). Requires find_contact: true"),
289
343
  // The API resolves a mix silently and wrongly (see the description), so
@@ -293,6 +347,7 @@ export function registerTools(server, { leadListBudgetMs = LEAD_LIST_BUDGET_MS }
293
347
  message: "Pass exactly [0], exactly [-1], or real list ids — never a marker mixed with other ids",
294
348
  })
295
349
  .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`."),
350
+ save_to_list_id: z.number().int().positive().optional().describe("Contact list to save every contact found into, from `list_contact_lists` or `create_contact_list`. Omit to save them to your contacts only. Only contacts with an email address can be read back from a list (`list_contacts`, and the web app alike), so with find_email false the list looks empty even when contacts were found."),
296
351
  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`."),
297
352
  },
298
353
  // Each call starts a new run and spends credits again, so it is not
@@ -310,6 +365,7 @@ export function registerTools(server, { leadListBudgetMs = LEAD_LIST_BUDGET_MS }
310
365
  find_phone = false,
311
366
  exclusion_list_ids,
312
367
  add_to_exclusion_list_id,
368
+ save_to_list_id,
313
369
  } = params;
314
370
 
315
371
  log(`generate_lead_list: limit=${limit} mode=${mode} find_contact=${find_contact} find_email=${find_email} find_phone=${find_phone}`);
@@ -332,6 +388,10 @@ export function registerTools(server, { leadListBudgetMs = LEAD_LIST_BUDGET_MS }
332
388
  config.exclusion_filter_list_ids = exclusion_list_ids;
333
389
  }
334
390
 
391
+ if (save_to_list_id !== undefined) {
392
+ config.lead_list_id = save_to_list_id;
393
+ }
394
+
335
395
  if (add_to_exclusion_list_id !== undefined) {
336
396
  config.add_to_exclusion_list = true;
337
397
  config.exclusion_list_id = add_to_exclusion_list_id;
@@ -367,14 +427,17 @@ export function registerTools(server, { leadListBudgetMs = LEAD_LIST_BUDGET_MS }
367
427
  "get_lead_list_results",
368
428
  toolConfig({
369
429
  title: "Get Lead List Results",
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`.",
430
+ description: `Follow a lead list run started with \`generate_lead_list\` and read its results one page at a time. Takes the hash returned by \`generate_lead_list\`. By default it waits for the run for up to ${LEAD_LIST_BUDGET_MS / 1000} seconds; set wait to false for a single status check that answers at once. While the run is going, returns status "processing" with its progress — call again to keep waiting. Once it is done, returns status "success" with one page of results under \`data\`, plus \`page\`, \`last_page\` and \`total\` (the number of rows in the whole run): pass page + 1 to read the next one while \`has_more\` is true. Only ask for the pages you need — a 5,000-row run is 50 pages at the default size, and each page lands in your context. Consumes no credits, whatever the number of pages read: the run itself was charged by \`generate_lead_list\`.`,
371
431
  inputSchema: {
372
432
  hash: z.string().describe("The hash returned by generate_lead_list"),
433
+ page: z.number().int().min(1).optional().default(1).describe("Page of results to return once the run is done (default: 1)"),
434
+ per_page: z.number().int().min(1).max(MAX_RESULTS_PER_PAGE).optional().default(DEFAULT_RESULTS_PER_PAGE).describe(`Rows per page (default: ${DEFAULT_RESULTS_PER_PAGE}, max: ${MAX_RESULTS_PER_PAGE})`),
435
+ wait: z.boolean().optional().default(true).describe(`Wait up to ${LEAD_LIST_BUDGET_MS / 1000}s for the run to finish (default), or false to check its status once and answer at once`),
373
436
  },
374
437
  annotations: READS,
375
438
  }),
376
- async ({ hash }, extra) => {
377
- log("get_lead_list_results");
439
+ async ({ hash, page = 1, per_page = DEFAULT_RESULTS_PER_PAGE, wait = true }, extra) => {
440
+ log(`get_lead_list_results: page=${page} per_page=${per_page} wait=${wait}`);
378
441
 
379
442
  const progressToken = extra._meta?.progressToken;
380
443
 
@@ -384,7 +447,8 @@ export function registerTools(server, { leadListBudgetMs = LEAD_LIST_BUDGET_MS }
384
447
  const deadline = Date.now() + leadListBudgetMs;
385
448
  // Each call gets what is left of the budget, never less than 1ms.
386
449
  const remaining = () => Math.max(1, deadline - Date.now());
387
- const stillProcessing = message => formatResponse({ status: "processing", hash, message });
450
+ const stillProcessing = (message, progress) => formatResponse({ status: "processing", hash, progress, message });
451
+ let lastProgress;
388
452
 
389
453
  for (let attempt = 1; ; attempt++) {
390
454
  let statusResult;
@@ -408,37 +472,44 @@ export function registerTools(server, { leadListBudgetMs = LEAD_LIST_BUDGET_MS }
408
472
  });
409
473
  }
410
474
 
411
- log(`get_lead_list_results: completed, fetching data...`);
412
-
413
- const allData = [];
414
- let currentPage = 1;
415
- let lastPage = 1;
416
- const perPage = 100;
475
+ log(`get_lead_list_results: completed, fetching page ${page}...`);
417
476
 
477
+ // One page per call, never the whole run: a 5,000-row export in a
478
+ // single response floods the agent's context.
479
+ const searchParams = new URLSearchParams({ hash, page: String(page), per_page: String(per_page) });
480
+ let dataResult;
418
481
  try {
419
- do {
420
- const dataResult = await apiGet(`/intellimatch/data?hash=${encodeURIComponent(hash)}&page=${currentPage}&per_page=${perPage}`, apiKey, { timeoutMs: remaining() });
482
+ dataResult = await apiGet(`/intellimatch/data?${searchParams.toString()}`, apiKey, { timeoutMs: remaining() });
483
+ } catch (error) {
484
+ // The run is done; only fetching the page ran out of time. A new
485
+ // call starts with a full budget and finds the status already done.
486
+ if (error.code !== "timeout") throw error;
487
+ log(`get_lead_list_results: page ${page} fetch timed out`);
488
+ return stillProcessing("Search is complete but this page of results could not be fetched in time. Call get_lead_list_results again with the same page to fetch it.", 100);
489
+ }
421
490
 
422
- if (dataResult.data && Array.isArray(dataResult.data)) {
423
- allData.push(...dataResult.data);
424
- }
491
+ const data = Array.isArray(dataResult.data) ? dataResult.data : [];
492
+ const meta = dataResult.meta;
425
493
 
426
- if (dataResult.meta) {
427
- lastPage = dataResult.meta.last_page || 1;
428
- }
494
+ // Without the paging metadata, the row count of one page says
495
+ // nothing about the run: report no total rather than a wrong one,
496
+ // and only a full page as a sign that another may follow.
497
+ if (!meta) {
498
+ log(`get_lead_list_results: page ${page}, ${data.length} rows, no paging metadata`);
499
+ return formatResponse({ status: "success", data, page, per_page, has_more: data.length >= per_page });
500
+ }
429
501
 
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.");
502
+ // The API reports last_page 0 for a run with no rows.
503
+ const lastPage = Math.max(1, meta.last_page ?? 1);
504
+ const response = { status: "success", data, page, per_page, last_page: lastPage, total: meta.total, has_more: page < lastPage };
505
+ // Past the end the API answers an empty page, which reads like an
506
+ // empty run unless said otherwise.
507
+ if (page > lastPage) {
508
+ response.message = `Page ${page} is past the last page (${lastPage}) of this run: there are no more results.`;
438
509
  }
439
510
 
440
- log(`get_lead_list_results: fetched ${allData.length} results`);
441
- return formatResponse({ status: "success", data: allData, total: allData.length });
511
+ log(`get_lead_list_results: page ${page}/${lastPage}, ${data.length} rows`);
512
+ return formatResponse(response);
442
513
  }
443
514
 
444
515
  // An unknown hash is a 200 with this status, not a 4xx: waiting on it
@@ -471,6 +542,11 @@ export function registerTools(server, { leadListBudgetMs = LEAD_LIST_BUDGET_MS }
471
542
  }
472
543
  }
473
544
  log(`get_lead_list_results: progress ${statusResult.progress ?? "in preparation"}`);
545
+ lastProgress = statusResult.progress;
546
+
547
+ if (!wait) {
548
+ return stillProcessing("Search is still processing. Call get_lead_list_results again later, or with wait left on to wait for it.", lastProgress);
549
+ }
474
550
 
475
551
  // Stop when a wait would leave no time for another check
476
552
  if (deadline - Date.now() <= POLL_INTERVAL_MS) break;
@@ -478,7 +554,67 @@ export function registerTools(server, { leadListBudgetMs = LEAD_LIST_BUDGET_MS }
478
554
  }
479
555
 
480
556
  // 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.`);
557
+ return stillProcessing(`Search is still processing after ${leadListBudgetMs / 1000} seconds. Call get_lead_list_results again to continue waiting.`, lastProgress);
558
+ } catch (error) {
559
+ return formatError(error.message);
560
+ }
561
+ }
562
+ );
563
+
564
+ // ===========================================================================
565
+ // Tool: get_credit_balance
566
+ // ===========================================================================
567
+ server.registerTool(
568
+ "get_credit_balance",
569
+ toolConfig({
570
+ title: "Get Credit Balance",
571
+ description: "Return the credits left on your account. Call it before starting a run that can spend many credits — a large `generate_lead_list`, or a loop of finder calls over hundreds of rows — so you can compare the estimated cost with what is left and ask the user before going ahead. Returns `credits` (finder credits left, used by every lookup tool and by lead lists), `verifier_credits` (credits left for `verify_email` — absent when the account is on unified pricing, where a single `credits` pool pays for everything) and `has_capacity`. Read them by plan: when `has_capacity` is null, the account buys credits and `credits` is exactly what it can spend. When `has_capacity` is true or false, the account is on a usage-capacity plan: spending first draws on rolling usage windows that refill over time, and `credits` is only an extra balance on top, often 0 — so `credits: 0` with `has_capacity: true` does not mean the run will be refused. `has_capacity` false means nothing is left right now; calls are refused until the windows refill. On a team, the balance and the capacity are the team owner's, shared by every member. Consumes no credits.",
572
+ inputSchema: {},
573
+ annotations: READS,
574
+ }),
575
+ async (params, extra) => {
576
+ log("get_credit_balance");
577
+
578
+ try {
579
+ const apiKey = resolveApiKey(extra);
580
+ // The endpoint also returns the caller's email and user id: nothing the
581
+ // agent needs to budget a run, so keep them out of the model's context.
582
+ const { email, id, ...balance } = await apiGet("/credits", apiKey);
583
+ return formatResponse(balance);
584
+ } catch (error) {
585
+ return formatError(error.message);
586
+ }
587
+ }
588
+ );
589
+
590
+ // ===========================================================================
591
+ // Tool: get_credit_usage
592
+ // ===========================================================================
593
+ server.registerTool(
594
+ "get_credit_usage",
595
+ toolConfig({
596
+ title: "Get Credit Usage",
597
+ description: "Report how many finder and verifier credits were spent over a date range. By default it covers your own usage, broken down by day — or by month when the range is longer than 2 months — under `items`, with the totals under `total`. Set team to true for a per-member summary of the whole team under `members`; only the team owner may do that, anyone else gets a 403. Use it to explain where credits went or to compare spend with what is left (`get_credit_balance`). On a usage-capacity plan (`has_capacity` not null in `get_credit_balance`), spend absorbed by the usage windows may not show here. Consumes no credits.",
598
+ inputSchema: {
599
+ from: reportDate().optional().describe("First day of the report, included (YYYY-MM-DD). Defaults to 30 days ago."),
600
+ to: reportDate().optional().describe("Last day of the report, included (YYYY-MM-DD). Defaults to today."),
601
+ team: z.boolean().optional().default(false).describe("Summarize every team member instead of your own usage. Team owner only."),
602
+ },
603
+ annotations: READS,
604
+ }),
605
+ async ({ from, to, team = false }, extra) => {
606
+ log(`get_credit_usage: team=${team} from=${from ?? "default"} to=${to ?? "default"}`);
607
+
608
+ try {
609
+ const apiKey = resolveApiKey(extra);
610
+
611
+ const searchParams = new URLSearchParams();
612
+ if (from) searchParams.set("from", from);
613
+ if (to) searchParams.set("to", to);
614
+ const query = searchParams.toString();
615
+
616
+ const data = await apiGet(`/credits/report/${team ? "team-summary" : "summary"}${query ? `?${query}` : ""}`, apiKey);
617
+ return formatResponse(data);
482
618
  } catch (error) {
483
619
  return formatError(error.message);
484
620
  }
@@ -640,4 +776,435 @@ export function registerTools(server, { leadListBudgetMs = LEAD_LIST_BUDGET_MS }
640
776
  }
641
777
  }
642
778
  );
779
+
780
+ // ===========================================================================
781
+ // Tool: search_technologies
782
+ // ===========================================================================
783
+ server.registerTool(
784
+ "search_technologies",
785
+ toolConfig({
786
+ title: "Search Technologies",
787
+ description: "Search the Findymail technology catalog by name and return up to 25 matches, each with its exact name, category and subcategory. Use it to check that a technology is known, and how it is spelled, before naming it in a `generate_lead_list` query (\"companies using HubSpot\") or filtering `get_company_technologies` on it. Rate-limited to 10 calls per minute. Consumes no credits.",
788
+ inputSchema: {
789
+ query: z.string().trim().min(2).max(100).describe("Technology name or part of it (min 2 characters, e.g. \"hubspot\")"),
790
+ },
791
+ annotations: READS,
792
+ }),
793
+ async ({ query }, extra) => {
794
+ log("search_technologies");
795
+
796
+ try {
797
+ const apiKey = resolveApiKey(extra);
798
+ const data = await apiGet(`/technologies/search?${new URLSearchParams({ q: query }).toString()}`, apiKey);
799
+ return formatResponse(data);
800
+ } catch (error) {
801
+ return formatError(error.message);
802
+ }
803
+ }
804
+ );
805
+
806
+ // ===========================================================================
807
+ // Tool: get_company_technologies
808
+ // ===========================================================================
809
+ server.registerTool(
810
+ "get_company_technologies",
811
+ toolConfig({
812
+ title: "Get Company Technologies",
813
+ description: `Return the technology stack detected for one company, identified by its domain: each technology with its name, category, subcategory and when it was last detected. Set technologies to only check for specific ones (case-insensitive names, e.g. [\"Salesforce\", \"HubSpot\"]) — an empty \`technologies\` array in the response then means none of them was detected. A large company can run hundreds of technologies, so at most limit of them are returned (default ${DEFAULT_TECHNOLOGIES_LIMIT}); \`total\` gives the full count and \`truncated\` is true when some were left out — narrow with technologies or categories rather than raising limit. Use it to qualify an account on its stack before prospecting it. Costs 1 finder credit when the company has at least one technology matching technologies (whatever categories and limit leave out of the response); an empty result is not charged.`,
814
+ inputSchema: {
815
+ domain: z.string().describe("Company domain (e.g. \"stripe.com\")"),
816
+ technologies: z.array(z.string()).max(50).optional().describe("Only return these technologies, matched by name, case-insensitively (max 50). Check exact names with `search_technologies`."),
817
+ categories: z.array(z.string()).min(1).optional().describe("Only return technologies in these categories, as `search_technologies` spells them (e.g. [\"sales\", \"marketing\"])"),
818
+ limit: z.number().int().min(1).max(MAX_TECHNOLOGIES_LIMIT).optional().default(DEFAULT_TECHNOLOGIES_LIMIT).describe(`Maximum number of technologies to return (default: ${DEFAULT_TECHNOLOGIES_LIMIT}, max: ${MAX_TECHNOLOGIES_LIMIT})`),
819
+ },
820
+ annotations: LOOKUP,
821
+ }),
822
+ async ({ domain, technologies, categories, limit = DEFAULT_TECHNOLOGIES_LIMIT }, extra) => {
823
+ log(`get_company_technologies: filter=${technologies?.length ?? 0} categories=${categories?.length ?? 0} limit=${limit}`);
824
+
825
+ try {
826
+ const apiKey = resolveApiKey(extra);
827
+ const body = { domain };
828
+ if (technologies?.length) body.technologies = technologies;
829
+ const data = await apiPost("/technologies", body, apiKey);
830
+
831
+ // The API filters by name only; categories and the cap are applied here.
832
+ if (!Array.isArray(data.technologies)) return formatResponse(data);
833
+ const wanted = categories && new Set(categories.map(category => category.toLowerCase()));
834
+ const matching = wanted
835
+ ? data.technologies.filter(technology => wanted.has(String(technology.category ?? "").toLowerCase()))
836
+ : data.technologies;
837
+
838
+ return formatResponse({
839
+ ...data,
840
+ technologies: matching.slice(0, limit),
841
+ total: matching.length,
842
+ truncated: matching.length > limit,
843
+ });
844
+ } catch (error) {
845
+ return formatError(error.message);
846
+ }
847
+ }
848
+ );
849
+
850
+ // ===========================================================================
851
+ // Tool: list_contact_lists
852
+ // ===========================================================================
853
+ server.registerTool(
854
+ "list_contact_lists",
855
+ toolConfig({
856
+ title: "List Contact Lists",
857
+ description: "List the contact lists you can use: the ones you own plus the ones shared with your team. A contact list holds people you found and saved — not to be confused with exclusion lists, which hold company domains to keep out of searches. Returns each list's id, name, whether it is shared with your team and whether you own it. Use the ids with `list_contacts`, `find_email` and `generate_lead_list` (to save what they find into a list), `create_monitor` (lead_list_id) and the other contact list tools. Consumes no credits.",
858
+ inputSchema: {},
859
+ annotations: READS,
860
+ }),
861
+ async (params, extra) => {
862
+ log("list_contact_lists");
863
+
864
+ try {
865
+ const apiKey = resolveApiKey(extra);
866
+ const data = await apiGet("/lists", apiKey);
867
+ return formatResponse(data);
868
+ } catch (error) {
869
+ return formatError(error.message);
870
+ }
871
+ }
872
+ );
873
+
874
+ // ===========================================================================
875
+ // Tool: create_contact_list
876
+ // ===========================================================================
877
+ server.registerTool(
878
+ "create_contact_list",
879
+ toolConfig({
880
+ title: "Create Contact List",
881
+ description: "Create a new, empty contact list and return it with its id. Fill it by passing that id to `find_email` (list_id) or `generate_lead_list` (save_to_list_id), or as lead_list_id to a monitor (`create_monitor`). Names are not unique: calling this twice creates two lists with the same name, so check `list_contact_lists` first. The list is private; share it with `update_contact_list`. Consumes no credits.",
882
+ inputSchema: {
883
+ name: z.string().trim().min(1).max(200).describe("Name of the list (max 200 characters)"),
884
+ },
885
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
886
+ }),
887
+ async ({ name }, extra) => {
888
+ log("create_contact_list");
889
+
890
+ try {
891
+ const apiKey = resolveApiKey(extra);
892
+ const data = await apiPost("/lists", { name }, apiKey);
893
+ return formatResponse(data);
894
+ } catch (error) {
895
+ return formatError(error.message);
896
+ }
897
+ }
898
+ );
899
+
900
+ // ===========================================================================
901
+ // Tool: update_contact_list
902
+ // ===========================================================================
903
+ server.registerTool(
904
+ "update_contact_list",
905
+ toolConfig({
906
+ title: "Update Contact List",
907
+ description: "Rename a contact list, or share it with your team or stop sharing it. Pass only what changes: whatever you omit keeps its current value. Only lists you may edit can be changed; anything else fails with a 403. Consumes no credits.",
908
+ inputSchema: {
909
+ list_id: z.number().int().positive().describe("List to change, from `list_contact_lists`"),
910
+ name: z.string().trim().min(1).max(200).optional().describe("New name (max 200 characters)"),
911
+ shared: z.boolean().optional().describe("true to share the list with your current team, false to stop sharing it"),
912
+ },
913
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
914
+ }),
915
+ async ({ list_id, name, shared }, extra) => {
916
+ log(`update_contact_list: list_id=${list_id} rename=${name !== undefined} shared=${shared ?? "unchanged"}`);
917
+
918
+ try {
919
+ if (name === undefined && shared === undefined) {
920
+ return formatError("Nothing to change: pass a new name, shared, or both");
921
+ }
922
+
923
+ const apiKey = resolveApiKey(extra);
924
+
925
+ // The API requires both the name and the sharing flag on every update,
926
+ // so a field the caller left out is read back rather than reset.
927
+ const { lists = [] } = await apiGet("/lists", apiKey);
928
+ const current = lists.find(list => list.id === list_id);
929
+ if (!current) {
930
+ return formatError(`No contact list ${list_id} among the lists you can use — check the id with \`list_contact_lists\``);
931
+ }
932
+
933
+ const data = await apiPut(`/lists/${list_id}`, {
934
+ name: name ?? current.name,
935
+ isShared: shared ?? Boolean(current.shared_with_team),
936
+ }, apiKey);
937
+ return formatResponse(data);
938
+ } catch (error) {
939
+ return formatError(error.message);
940
+ }
941
+ }
942
+ );
943
+
944
+ // ===========================================================================
945
+ // Tool: delete_contact_list
946
+ // ===========================================================================
947
+ server.registerTool(
948
+ "delete_contact_list",
949
+ toolConfig({
950
+ title: "Delete Contact List",
951
+ description: "Delete a contact list. This is irreversible: the list and its grouping of contacts are gone for good, for you and for every teammate it was shared with, and there is no undo. The contacts themselves are not deleted — they stay in your saved contacts (`list_contacts` with list_id 0). Confirm with the user before calling it. Consumes no credits.",
952
+ inputSchema: {
953
+ list_id: z.number().int().positive().describe("List to delete, from `list_contact_lists`"),
954
+ },
955
+ // A second call fails with a 404 once the list is gone.
956
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
957
+ }),
958
+ async ({ list_id }, extra) => {
959
+ log(`delete_contact_list: list_id=${list_id}`);
960
+
961
+ try {
962
+ const apiKey = resolveApiKey(extra);
963
+ await apiDelete(`/lists/${list_id}`, undefined, apiKey);
964
+ return formatResponse({ deleted: true, list_id });
965
+ } catch (error) {
966
+ return formatError(error.message);
967
+ }
968
+ }
969
+ );
970
+
971
+ // ===========================================================================
972
+ // Tool: list_contacts
973
+ // ===========================================================================
974
+ server.registerTool(
975
+ "list_contacts",
976
+ toolConfig({
977
+ title: "List Saved Contacts",
978
+ description: "Read back contacts you saved, one page at a time: from one contact list, or from all your saved contacts with list_id 0. Each contact comes with its id, name, email, LinkedIn URL, company and job title; only contacts with an email address are returned. Page with offset and limit, and keep going while `has_more` is true. The API gives no total count and no guaranteed order, so a contact saved while you page may shift the pages. Consumes no credits.",
979
+ inputSchema: {
980
+ list_id: z.number().int().min(0).optional().default(0).describe("Contact list to read, from `list_contact_lists`. 0 (default) reads all your saved contacts."),
981
+ offset: z.number().int().min(0).optional().default(0).describe("Number of contacts to skip (default: 0)"),
982
+ limit: z.number().int().min(1).max(MAX_CONTACTS_PER_PAGE).optional().default(DEFAULT_CONTACTS_PER_PAGE).describe(`Contacts to return (default: ${DEFAULT_CONTACTS_PER_PAGE}, max: ${MAX_CONTACTS_PER_PAGE})`),
983
+ },
984
+ annotations: READS,
985
+ }),
986
+ async ({ list_id = 0, offset = 0, limit = DEFAULT_CONTACTS_PER_PAGE }, extra) => {
987
+ log(`list_contacts: list_id=${list_id} offset=${offset} limit=${limit}`);
988
+
989
+ try {
990
+ const apiKey = resolveApiKey(extra);
991
+
992
+ // Without start and length the endpoint returns every contact at once.
993
+ const searchParams = new URLSearchParams({ start: String(offset), length: String(limit) });
994
+ const data = await apiGet(`/contacts/get/${list_id}?${searchParams.toString()}`, apiKey);
995
+
996
+ // recordsTotal and recordsFiltered are a fixed placeholder server-side,
997
+ // not a count: passing them on would mislead the agent.
998
+ const contacts = Array.isArray(data.data) ? data.data : [];
999
+ return formatResponse({ contacts, offset, limit, has_more: contacts.length === limit });
1000
+ } catch (error) {
1001
+ return formatError(error.message);
1002
+ }
1003
+ }
1004
+ );
1005
+
1006
+ // ===========================================================================
1007
+ // Tool: list_signals
1008
+ // ===========================================================================
1009
+ server.registerTool(
1010
+ "list_signals",
1011
+ toolConfig({
1012
+ title: "List Signals",
1013
+ description: "List the buying signals your monitors detected (yours and your team's shared ones), most recent first, one page at a time. Each signal comes with its type, the matching contact and company, what triggered it (keyword, post, new job…) and the monitors that caught it, with their AI relevance score when one is configured. Filter by type, monitor, detection date or relevance score. Read a single signal with `get_signal`, and manage what is watched with the monitor tools. Consumes no credits: signals are charged when a monitor delivers them.",
1014
+ inputSchema: {
1015
+ signal_type: z.enum(SIGNAL_TYPES).optional().describe("Only this type of signal"),
1016
+ monitor_id: z.number().int().positive().optional().describe("Only signals caught by this monitor, from `list_monitors`"),
1017
+ date_from: reportDate().optional().describe("Only signals detected on or after this day (YYYY-MM-DD)"),
1018
+ date_to: reportDate().optional().describe("Only signals detected on or before this day (YYYY-MM-DD)"),
1019
+ relevance_scores: z.array(z.number().int().min(0).max(5)).min(1).max(6).optional().describe("Only signals whose AI relevance score is one of these (0-5, e.g. [4, 5]). Scores exist only on monitors with an ai_relevance_prompt; combine with monitor_id to score against one monitor."),
1020
+ ownership: z.enum(["my", "team", "all"]).optional().describe("Only signals from your own monitors (my), your teammates' shared ones (team), or both (all, default)"),
1021
+ page: z.number().int().min(1).optional().default(1).describe("Page number (default: 1)"),
1022
+ per_page: z.number().int().min(1).max(100).optional().default(50).describe("Signals per page (default: 50, max: 100)"),
1023
+ },
1024
+ annotations: READS,
1025
+ }),
1026
+ async (params, extra) => {
1027
+ const { page = 1, per_page = 50 } = params;
1028
+ log(`list_signals: type=${params.signal_type ?? "any"} monitor=${params.monitor_id ?? "any"} page=${page}`);
1029
+
1030
+ try {
1031
+ const apiKey = resolveApiKey(extra);
1032
+
1033
+ const searchParams = new URLSearchParams({ page: String(page), per_page: String(per_page) });
1034
+ for (const key of ["signal_type", "monitor_id", "date_from", "date_to", "ownership"]) {
1035
+ if (params[key] !== undefined) searchParams.set(key, String(params[key]));
1036
+ }
1037
+ if (params.relevance_scores) searchParams.set("relevance_scores", params.relevance_scores.join(","));
1038
+
1039
+ const data = await apiGet(`/signals?${searchParams.toString()}`, apiKey);
1040
+ return formatResponse(data);
1041
+ } catch (error) {
1042
+ return formatError(error.message);
1043
+ }
1044
+ }
1045
+ );
1046
+
1047
+ // ===========================================================================
1048
+ // Tool: get_signal
1049
+ // ===========================================================================
1050
+ server.registerTool(
1051
+ "get_signal",
1052
+ toolConfig({
1053
+ title: "Get Signal",
1054
+ description: "Read one signal by id, as returned by `list_signals`: its type, what triggered it, the matching contact and company, and which of your monitors caught it. Signals you have no access to fail with a 403. Consumes no credits.",
1055
+ inputSchema: {
1056
+ signal_id: z.number().int().positive().describe("Signal id, from `list_signals`"),
1057
+ },
1058
+ annotations: READS,
1059
+ }),
1060
+ async ({ signal_id }, extra) => {
1061
+ log(`get_signal: signal_id=${signal_id}`);
1062
+
1063
+ try {
1064
+ const apiKey = resolveApiKey(extra);
1065
+ const data = await apiGet(`/signals/${signal_id}`, apiKey);
1066
+ return formatResponse(data);
1067
+ } catch (error) {
1068
+ return formatError(error.message);
1069
+ }
1070
+ }
1071
+ );
1072
+
1073
+ // ===========================================================================
1074
+ // Tool: list_monitors
1075
+ // ===========================================================================
1076
+ server.registerTool(
1077
+ "list_monitors",
1078
+ toolConfig({
1079
+ title: "List Monitors",
1080
+ description: "List the signal monitors you can see — yours and the ones teammates shared — most recent first. A monitor watches LinkedIn and job boards for one kind of buying signal and delivers each match as a signal. Returns each monitor's id, name, type, status (active or paused), filters, enrichment level, contact list, match cap and match_count. Use the ids with `list_signals`, `update_monitor` and `delete_monitor`. Consumes no credits.",
1081
+ inputSchema: {
1082
+ ownership: z.enum(["my", "team", "all"]).optional().describe("Only your own monitors (my), your teammates' shared ones (team), or both (all, default)"),
1083
+ },
1084
+ annotations: READS,
1085
+ }),
1086
+ async ({ ownership }, extra) => {
1087
+ log(`list_monitors: ownership=${ownership ?? "all"}`);
1088
+
1089
+ try {
1090
+ const apiKey = resolveApiKey(extra);
1091
+ const data = await apiGet(`/signals/monitors${ownership ? `?ownership=${ownership}` : ""}`, apiKey);
1092
+ return formatResponse(data);
1093
+ } catch (error) {
1094
+ return formatError(error.message);
1095
+ }
1096
+ }
1097
+ );
1098
+
1099
+ // ===========================================================================
1100
+ // Tool: create_monitor
1101
+ // ===========================================================================
1102
+ server.registerTool(
1103
+ "create_monitor",
1104
+ toolConfig({
1105
+ title: "Create Monitor",
1106
+ description: `Create a signal monitor that keeps running in the background and delivers every match as a signal (read them with \`list_signals\`). Types: "keyword_mention" (LinkedIn posts mentioning keywords — keywords required), "post_engagement" (people who like or comment a LinkedIn post or profile's posts — engagement_types plus post_url, profile_url or keywords), "new_hire" and "job_change" (people starting a new job — target_companies or icp_filters required), "company_hiring" (companies posting job offers — job_offer_title_keywords required, enrichment_level must be "none"). The API answers a 422 naming any missing or forbidden field for the type. COST: every signal delivered charges finder credits for as long as the monitor runs — ${SIGNAL_BASE_COST} credit per signal for new_hire, job_change and company_hiring; for keyword_mention and post_engagement, ${SIGNAL_BASE_COST} plus 1 with company-level icp_filters (industries, sizes, countries) and 1 more with contact-level ones (job titles, seniority), so up to 3. Set max_matches to cap the total spend: the monitor pauses itself once it is reached. Plans limit how many monitors can be active at once. Get the user's go-ahead on the type, filters and match cap before creating one.`,
1107
+ inputSchema: {
1108
+ signal_type: z.enum(SIGNAL_TYPES).describe("Kind of signal to watch for (cannot be changed later)"),
1109
+ ...MONITOR_FIELDS,
1110
+ post_url: z.string().url().max(2048).optional().describe("post_engagement only: HTTPS URL of the LinkedIn post to watch. Not with profile_url."),
1111
+ profile_url: z.string().url().max(2048).optional().describe("post_engagement only: HTTPS URL of the LinkedIn profile whose posts to watch. Not with post_url."),
1112
+ max_matches: z.number().int().min(1).max(MAX_MONITOR_MATCHES).optional().describe(`Lifetime cap on signals delivered, and so on credits spent (1-${MAX_MONITOR_MATCHES}). Omit for no cap.`),
1113
+ },
1114
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
1115
+ }),
1116
+ async (params, extra) => {
1117
+ log(`create_monitor: type=${params.signal_type} enrichment=${params.enrichment_level ?? "default"} max_matches=${params.max_matches ?? "none"}`);
1118
+
1119
+ try {
1120
+ const apiKey = resolveApiKey(extra);
1121
+ const data = await apiPost("/signals/monitors", params, apiKey);
1122
+ return formatResponse(data);
1123
+ } catch (error) {
1124
+ return formatError(error.message);
1125
+ }
1126
+ }
1127
+ );
1128
+
1129
+ // ===========================================================================
1130
+ // Tool: update_monitor
1131
+ // ===========================================================================
1132
+ server.registerTool(
1133
+ "update_monitor",
1134
+ toolConfig({
1135
+ title: "Update Monitor",
1136
+ description: "Change a monitor's settings. Pass only what changes: whatever you omit keeps its current value. The type, post_url and profile_url cannot be changed — delete the monitor and create a new one instead. A list or icp_filters you pass replaces the current one entirely (keywords: [\"a\"] drops every other keyword); pass an empty one to clear it where the monitor type allows. max_matches, ai_relevance_prompt and lead_list_id are cleared with null. Lowering max_matches below the current match_count pauses the monitor. Changing filters changes the credits charged per signal (see `create_monitor`). Consumes no credits by itself.",
1137
+ inputSchema: {
1138
+ monitor_id: z.number().int().positive().describe("Monitor to change, from `list_monitors`"),
1139
+ ...MONITOR_FIELDS,
1140
+ name: MONITOR_FIELDS.name.optional(),
1141
+ // Nullable inside the optional, not around it: the other way round
1142
+ // generates an anyOf with an empty `not` branch that clients choke on.
1143
+ lead_list_id: MONITOR_FIELDS.lead_list_id.unwrap().nullable().optional().describe(`${MONITOR_FIELDS.lead_list_id.description}; null stops saving matches to a list`),
1144
+ ai_relevance_prompt: MONITOR_FIELDS.ai_relevance_prompt.unwrap().nullable().optional().describe(`${MONITOR_FIELDS.ai_relevance_prompt.description}; null removes the scoring`),
1145
+ max_matches: z.number().int().min(1).max(MAX_MONITOR_MATCHES).nullable().optional().describe(`Lifetime cap on signals delivered (1-${MAX_MONITOR_MATCHES}); null removes the cap`),
1146
+ },
1147
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
1148
+ }),
1149
+ async ({ monitor_id, ...changes }, extra) => {
1150
+ log(`update_monitor: monitor_id=${monitor_id} fields=${Object.keys(changes).sort().join(",")}`);
1151
+
1152
+ try {
1153
+ if (Object.keys(changes).length === 0) {
1154
+ return formatError("Nothing to change: pass at least one field to update");
1155
+ }
1156
+
1157
+ const apiKey = resolveApiKey(extra);
1158
+
1159
+ // The API resets name, enrichment_level and lead_list_id when they are
1160
+ // left out of an update, unlike every other field: read them back so an
1161
+ // omitted field keeps its value, as the description promises.
1162
+ const listed = await apiGet("/signals/monitors", apiKey);
1163
+ const monitors = Array.isArray(listed) ? listed : listed.data ?? [];
1164
+ const current = monitors.find(monitor => monitor.id === monitor_id);
1165
+ if (!current) {
1166
+ return formatError(`No monitor ${monitor_id} among the monitors you can see — check the id with \`list_monitors\``);
1167
+ }
1168
+
1169
+ const body = {
1170
+ name: current.name,
1171
+ enrichment_level: current.enrichment_level,
1172
+ lead_list_id: current.lead_list_id,
1173
+ ...changes,
1174
+ };
1175
+
1176
+ const data = await apiPatch(`/signals/monitors/${monitor_id}`, body, apiKey);
1177
+ return formatResponse(data);
1178
+ } catch (error) {
1179
+ return formatError(error.message);
1180
+ }
1181
+ }
1182
+ );
1183
+
1184
+ // ===========================================================================
1185
+ // Tool: delete_monitor
1186
+ // ===========================================================================
1187
+ server.registerTool(
1188
+ "delete_monitor",
1189
+ toolConfig({
1190
+ title: "Delete Monitor",
1191
+ description: "Delete a signal monitor: it stops watching and stops charging credits at once. This is irreversible — neither the API nor these tools can restore it, for you or for teammates it was shared with; recreating it starts a new monitor from zero. Signals are only readable through a monitor that still exists, so the ones only this monitor caught disappear from `list_signals` and `get_signal` with it — export what the user wants to keep first. Confirm with the user before calling it. Consumes no credits.",
1192
+ inputSchema: {
1193
+ monitor_id: z.number().int().positive().describe("Monitor to delete, from `list_monitors`"),
1194
+ },
1195
+ // A second call fails with a 404 once the monitor is gone.
1196
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
1197
+ }),
1198
+ async ({ monitor_id }, extra) => {
1199
+ log(`delete_monitor: monitor_id=${monitor_id}`);
1200
+
1201
+ try {
1202
+ const apiKey = resolveApiKey(extra);
1203
+ await apiDelete(`/signals/monitors/${monitor_id}`, undefined, apiKey);
1204
+ return formatResponse({ deleted: true, monitor_id });
1205
+ } catch (error) {
1206
+ return formatError(error.message);
1207
+ }
1208
+ }
1209
+ );
643
1210
  }