@codegame.dev/careerflow-mcp 2.1.0 → 3.0.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/dist/tools/crm.js CHANGED
@@ -1,37 +1,189 @@
1
1
  import { z } from "zod";
2
2
  import { boolParam, companyIdSchema, extractList, resolveCompanyId, safeHandler, textResult } from "../helpers.js";
3
3
  /**
4
- * CRM tools: contacts (leads and customers), deals, and activities.
4
+ * CRM tools on the Salesforce-style model: leads, accounts, contacts, deals and
5
+ * activities.
5
6
  *
6
- * Contacts carry a dual identity: a `contact_status` of `lead` moves through a
7
- * pipeline/stage, while `customer` is a settled state. The API derives status
8
- * from the pipeline/stage rather than accepting it directly on edit, so these
9
- * tools never expose `contact_status` as a writable field.
7
+ * - A **lead** is an unqualified, flat person-at-company prospect on a lead
8
+ * pipeline. It ends either converted (crm_convert_lead creates or matches an
9
+ * account and a contact, optionally a deal; the lead then becomes read-only)
10
+ * or disqualified (crm_disqualify_lead, with a reason). There is no undo.
11
+ * - An **account** is an organization; a **contact** is a person, optionally
12
+ * linked to a primary account. Their `lifecycle_stage` (prospect /
13
+ * opportunity / customer) is derived from deals and never written.
14
+ * - A **deal** belongs to an account and/or a primary contact (at least one),
15
+ * never to a lead.
16
+ * - An **activity** links a Who (Lead or Contact) and/or a What (Account or
17
+ * Deal).
10
18
  */
11
- const contactTypeSchema = z.enum(["individual", "corporation"]);
12
- const relatedToTypeSchema = z.enum(["Contact", "Deal"]);
19
+ const lifecycleSchema = z.enum(["prospect", "opportunity", "customer"]);
20
+ const accountTypeSchema = z.enum(["partner", "reseller", "supplier", "influencer", "competitor", "other"]);
21
+ const whoTypeSchema = z.enum(["Lead", "Contact"]);
22
+ const whatTypeSchema = z.enum(["Account", "Deal"]);
23
+ const customFieldValuesSchema = z
24
+ .record(z.unknown())
25
+ .refine((values) => Object.keys(values).length > 0, "Pass at least one field_key.")
26
+ .optional()
27
+ .describe("Custom field values keyed by field_key (see crm_list_custom_fields). Replaces the stored set.");
28
+ const listParams = {
29
+ is_active: z.boolean().optional().default(true),
30
+ limit: z.number().int().min(1).max(50).optional().default(20),
31
+ page: z.number().int().min(1).optional().default(1),
32
+ order_by: z.string().optional().default("created"),
33
+ direction: z.enum(["asc", "desc"]).optional().default("desc")
34
+ };
35
+ const addressParams = {
36
+ address: z.string().optional(),
37
+ city: z.string().optional(),
38
+ state: z.string().optional(),
39
+ postal_code: z.string().optional(),
40
+ country: z.string().optional()
41
+ };
42
+ const leadFieldParams = {
43
+ firstname: z.string().optional(),
44
+ lastname: z.string().optional(),
45
+ email: z.string().optional(),
46
+ phone: z.string().optional(),
47
+ mobile: z.string().optional(),
48
+ title: z.string().optional().describe("Job title."),
49
+ department: z.string().optional(),
50
+ national_id: z.string().optional(),
51
+ company_name: z.string().optional().describe("The prospect's organization (becomes the account on convert)."),
52
+ website: z.string().optional(),
53
+ industry: z.string().optional(),
54
+ employee_count: z.number().int().optional(),
55
+ economic_code: z.string().optional(),
56
+ registration_number: z.string().optional(),
57
+ customer_code: z.string().optional(),
58
+ ...addressParams,
59
+ lead_source_id: z.number().int().optional(),
60
+ rating: z.number().int().optional(),
61
+ owner_user_id: z.number().int().optional(),
62
+ lead_score: z.number().int().optional(),
63
+ next_step: z.string().max(255).optional(),
64
+ notes: z.string().optional(),
65
+ custom_field_values: customFieldValuesSchema
66
+ };
67
+ const accountFieldParams = {
68
+ account_type: accountTypeSchema.optional(),
69
+ website: z.string().optional(),
70
+ industry: z.string().optional(),
71
+ employee_count: z.number().int().optional(),
72
+ economic_code: z.string().optional(),
73
+ registration_number: z.string().optional(),
74
+ customer_code: z.string().optional().describe("Generated from the company's series when omitted on create."),
75
+ credit_limit: z.number().optional(),
76
+ payment_terms_days: z.number().int().optional(),
77
+ currency_id: z.number().int().optional(),
78
+ phone: z.string().optional(),
79
+ mobile: z.string().optional(),
80
+ email: z.string().optional(),
81
+ ...addressParams,
82
+ lead_source_id: z.number().int().optional(),
83
+ rating: z.number().int().optional(),
84
+ owner_user_id: z.number().int().optional(),
85
+ notes: z.string().optional(),
86
+ custom_field_values: customFieldValuesSchema
87
+ };
88
+ const contactFieldParams = {
89
+ firstname: z.string().optional(),
90
+ lastname: z.string().optional(),
91
+ email: z.string().optional(),
92
+ phone: z.string().optional(),
93
+ mobile: z.string().optional(),
94
+ title: z.string().optional().describe("Job title."),
95
+ department: z.string().optional(),
96
+ national_id: z.string().optional(),
97
+ customer_code: z.string().optional(),
98
+ ...addressParams,
99
+ lead_source_id: z.number().int().optional(),
100
+ rating: z.number().int().optional(),
101
+ owner_user_id: z.number().int().optional(),
102
+ notes: z.string().optional(),
103
+ custom_field_values: customFieldValuesSchema
104
+ };
105
+ /** Copies the named args that were passed into a request body. */
106
+ function pick(args, keys) {
107
+ const out = {};
108
+ for (const key of keys) {
109
+ if (args[key] !== undefined)
110
+ out[key] = args[key];
111
+ }
112
+ return out;
113
+ }
114
+ const personName = (first, last) => [first, last].filter(Boolean).join(" ") || undefined;
115
+ const label = (name) => name?.en || name?.fa || undefined;
116
+ const flag = (value) => (value === undefined || value === null ? undefined : Boolean(value));
117
+ const tagNames = (tags) => Array.isArray(tags) ? tags.map((t) => t.name?.en || t.name?.fa || t.name_fa) : undefined;
118
+ function summariseLead(l) {
119
+ return {
120
+ id: l.id,
121
+ name: personName(l.firstname, l.lastname),
122
+ company_name: l.company_name || undefined,
123
+ title: l.title || undefined,
124
+ email: l.email || undefined,
125
+ phone: l.phone || undefined,
126
+ mobile: l.mobile || undefined,
127
+ lead_pipeline_id: l.lead_pipeline_id ?? undefined,
128
+ lead_pipeline: label(l.lead_pipeline_name),
129
+ lead_stage_id: l.lead_stage_id ?? undefined,
130
+ lead_stage: label(l.lead_stage_name),
131
+ stage_type: l.lead_stage_type || undefined,
132
+ lead_source: label(l.lead_source_name),
133
+ lead_score: l.lead_score ?? undefined,
134
+ rating: l.rating ?? undefined,
135
+ owner: personName(l.owner_firstname, l.owner_lastname),
136
+ is_converted: flag(l.is_converted),
137
+ converted_account_id: l.converted_account_id ?? undefined,
138
+ converted_contact_id: l.converted_contact_id ?? undefined,
139
+ converted_deal_id: l.converted_deal_id ?? undefined,
140
+ disqualify_reason: label(l.disqualify_reason_name),
141
+ disqualify_note: l.disqualify_note || undefined,
142
+ is_active: flag(l.is_active),
143
+ tags: tagNames(l.tags),
144
+ created: l.created,
145
+ updated: l.updated
146
+ };
147
+ }
148
+ function summariseAccount(a) {
149
+ return {
150
+ id: a.id,
151
+ name: a.name,
152
+ account_type: a.account_type || undefined,
153
+ lifecycle_stage: a.lifecycle_stage,
154
+ customer_since: a.customer_since || undefined,
155
+ customer_code: a.customer_code || undefined,
156
+ email: a.email || undefined,
157
+ phone: a.phone || undefined,
158
+ mobile: a.mobile || undefined,
159
+ industry: a.industry || undefined,
160
+ person_count: a.person_count ?? undefined,
161
+ lead_source: label(a.lead_source_name),
162
+ owner: personName(a.owner_firstname, a.owner_lastname),
163
+ is_active: flag(a.is_active),
164
+ tags: tagNames(a.tags),
165
+ created: a.created,
166
+ updated: a.updated
167
+ };
168
+ }
13
169
  function summariseContact(c) {
14
170
  return {
15
171
  id: c.id,
16
- contact_type: c.contact_type,
17
- contact_status: c.contact_status,
18
- name: c.contact_type === "corporation"
19
- ? c.corporation_name
20
- : [c.firstname, c.lastname].filter(Boolean).join(" ") || undefined,
172
+ name: personName(c.firstname, c.lastname),
173
+ title: c.title || undefined,
21
174
  email: c.email || undefined,
22
175
  phone: c.phone || undefined,
23
176
  mobile: c.mobile || undefined,
24
- parent_id: c.parent_id ?? undefined,
25
- child_count: c.child_count ?? undefined,
177
+ account_id: c.account_id ?? undefined,
178
+ account_name: c.account_name || undefined,
179
+ account_count: c.account_count ?? undefined,
180
+ lifecycle_stage: c.lifecycle_stage,
181
+ customer_since: c.customer_since || undefined,
26
182
  customer_code: c.customer_code || undefined,
27
- lead_source: c.lead_source_name?.en ?? undefined,
28
- lead_pipeline: c.lead_pipeline_name?.en ?? undefined,
29
- lead_stage: c.lead_stage || undefined,
30
- lead_score: c.lead_score ?? undefined,
31
- rating: c.rating ?? undefined,
32
- account_owner: [c.account_owner_firstname, c.account_owner_lastname].filter(Boolean).join(" ") || undefined,
33
- is_active: c.is_active === undefined ? undefined : Boolean(c.is_active),
34
- tags: Array.isArray(c.tags) ? c.tags.map((t) => t.name?.en ?? t.name_fa) : undefined,
183
+ lead_source: label(c.lead_source_name),
184
+ owner: personName(c.owner_firstname, c.owner_lastname),
185
+ is_active: flag(c.is_active),
186
+ tags: tagNames(c.tags),
35
187
  created: c.created,
36
188
  updated: c.updated
37
189
  };
@@ -40,22 +192,23 @@ function summariseDeal(d) {
40
192
  return {
41
193
  id: d.id,
42
194
  deal_name: d.deal_name,
43
- contact_id: d.contact_id,
44
- contact_name: d.contact_corporation_name ||
45
- [d.contact_firstname, d.contact_lastname].filter(Boolean).join(" ") ||
46
- undefined,
195
+ account_id: d.account_id ?? undefined,
196
+ account_name: d.account_name || undefined,
197
+ primary_contact_id: d.primary_contact_id ?? undefined,
198
+ primary_contact_name: personName(d.primary_contact_firstname, d.primary_contact_lastname),
199
+ converted_from_lead_id: d.converted_from_lead_id ?? undefined,
47
200
  pipeline_id: d.pipeline_id,
48
- pipeline: d.pipeline_name?.en ?? undefined,
201
+ pipeline: label(d.pipeline_name),
49
202
  stage_id: d.stage_id,
50
- stage: d.stage_name?.en ?? undefined,
51
- stage_is_won: d.stage_is_won === undefined ? undefined : Boolean(d.stage_is_won),
52
- stage_is_lost: d.stage_is_lost === undefined ? undefined : Boolean(d.stage_is_lost),
203
+ stage: label(d.stage_name),
204
+ stage_is_won: flag(d.stage_is_won),
205
+ stage_is_lost: flag(d.stage_is_lost),
53
206
  amount: d.amount ?? undefined,
54
207
  currency_id: d.currency_id ?? undefined,
55
208
  probability: d.probability ?? undefined,
56
209
  expected_close_date: d.expected_close_date || undefined,
57
210
  actual_close_date: d.actual_close_date || undefined,
58
- assigned_to: [d.assigned_to_firstname, d.assigned_to_lastname].filter(Boolean).join(" ") || undefined,
211
+ assigned_to: personName(d.assigned_to_firstname, d.assigned_to_lastname),
59
212
  next_step: d.next_step || undefined,
60
213
  lost_reason: d.lost_reason || undefined,
61
214
  created: d.created,
@@ -67,221 +220,383 @@ function summariseActivity(a) {
67
220
  id: a.id,
68
221
  activity_type: a.activity_type,
69
222
  subject: a.subject,
70
- related_to_type: a.related_to_type,
71
- related_to_id: a.related_to_id,
72
- contact_id: a.contact_id ?? undefined,
223
+ who_type: a.who_type ?? undefined,
224
+ who_id: a.who_id ?? undefined,
225
+ who_name: a.who_name || undefined,
226
+ what_type: a.what_type ?? undefined,
227
+ what_id: a.what_id ?? undefined,
228
+ what_name: a.what_name || undefined,
73
229
  status: a.status,
74
230
  priority: a.priority,
75
231
  due_date: a.due_date || undefined,
76
232
  completed_at: a.completed_at || undefined,
77
- assigned_to: [a.assigned_to_firstname, a.assigned_to_lastname].filter(Boolean).join(" ") || undefined,
233
+ assigned_to: personName(a.assigned_to_firstname, a.assigned_to_lastname),
78
234
  outcome: a.outcome || undefined,
79
235
  created: a.created
80
236
  };
81
237
  }
82
- export function registerCrmTools(server, client) {
83
- // ---------------------------------------------------------------- contacts
84
- server.registerTool("crm_search_contacts", {
85
- title: "Search CRM contacts",
86
- description: "Search leads and customers. A 'lead' moves through lead_pipeline_id/lead_stage_id; a " +
87
- "'customer' is settled. Use crm_list_pipelines to resolve pipeline/stage ids.",
238
+ const leadKeys = Object.keys(leadFieldParams);
239
+ const accountKeys = Object.keys(accountFieldParams);
240
+ const contactKeys = ["account_id", ...Object.keys(contactFieldParams)];
241
+ /** search / get / delete / timeline for one record type; the three share one route shape. */
242
+ function registerRecordTools(server, client, o) {
243
+ const path = `crm/${o.plural}`;
244
+ const idKey = `${o.kind}_id`;
245
+ server.registerTool(`crm_search_${o.plural}`, {
246
+ title: `Search CRM ${o.plural}`,
247
+ description: o.searchDescription,
248
+ inputSchema: { company_id: companyIdSchema, search: z.string().optional(), ...o.filters, ...listParams }
249
+ }, safeHandler(async (args) => {
250
+ const companyId = resolveCompanyId(client, args.company_id);
251
+ const query = { company_id: companyId };
252
+ for (const [key, value] of Object.entries(args)) {
253
+ if (key !== "company_id")
254
+ query[key] = typeof value === "boolean" ? boolParam(value) : value;
255
+ }
256
+ const response = await client.get(`${path}/search`, query);
257
+ const { items, total } = extractList(response.data, o.plural);
258
+ return textResult({ count: total ?? items.length, [o.plural]: items.map(o.summarise) });
259
+ }));
260
+ server.registerTool(`crm_get_${o.kind}`, {
261
+ title: `Get a CRM ${o.kind}`,
262
+ description: o.getDescription,
263
+ inputSchema: { company_id: companyIdSchema, [idKey]: z.number().int() }
264
+ }, safeHandler(async (args) => {
265
+ const companyId = resolveCompanyId(client, args.company_id);
266
+ const response = await client.get(`${path}/${args[idKey]}`, { company_id: companyId });
267
+ return textResult(response.data);
268
+ }));
269
+ server.registerTool(`crm_delete_${o.kind}`, {
270
+ title: `Delete a CRM ${o.kind}`,
271
+ description: o.deleteDescription,
272
+ inputSchema: { company_id: companyIdSchema, [idKey]: z.number().int() }
273
+ }, safeHandler(async (args) => {
274
+ const companyId = resolveCompanyId(client, args.company_id);
275
+ await client.post(`${path}/delete/${args[idKey]}`, { company_id: companyId });
276
+ return textResult({ deleted: true, [idKey]: args[idKey] });
277
+ }));
278
+ server.registerTool(`crm_${o.kind}_timeline`, {
279
+ title: `Get a ${o.kind}'s activity timeline`,
280
+ description: o.timelineDescription,
88
281
  inputSchema: {
89
282
  company_id: companyIdSchema,
90
- search: z.string().optional(),
91
- contact_type: contactTypeSchema.optional(),
92
- contact_status: z.enum(["lead", "customer", "lost"]).optional(),
283
+ [idKey]: z.number().int(),
284
+ limit: z.number().int().min(1).max(100).optional().default(20),
285
+ page: z.number().int().min(1).optional().default(1)
286
+ }
287
+ }, safeHandler(async (args) => {
288
+ const companyId = resolveCompanyId(client, args.company_id);
289
+ const response = await client.get(`${path}/${args[idKey]}/timeline`, {
290
+ company_id: companyId,
291
+ limit: args.limit,
292
+ page: args.page
293
+ });
294
+ const { items, total } = extractList(response.data, "activities");
295
+ return textResult({ count: total ?? items.length, activities: items.map(summariseActivity) });
296
+ }));
297
+ }
298
+ export function registerCrmTools(server, client) {
299
+ // ------------------------------------------------------------------ leads
300
+ registerRecordTools(server, client, {
301
+ kind: "lead",
302
+ plural: "leads",
303
+ summarise: summariseLead,
304
+ searchDescription: "Search leads (unqualified prospects on a lead pipeline). stage_type filters open, converted " +
305
+ "or disqualified leads. Use crm_list_pipelines kind 'lead' to resolve pipeline/stage ids.",
306
+ getDescription: "Fetch one lead in full, including tags, products, locations and its conversion result.",
307
+ timelineDescription: "Chronological feed of activities logged on a lead.",
308
+ deleteDescription: "Soft-delete a lead.",
309
+ filters: {
93
310
  lead_pipeline_id: z.number().int().optional(),
94
311
  lead_stage_id: z.number().int().optional(),
312
+ stage_type: z.enum(["open", "converted", "disqualified"]).optional(),
313
+ is_converted: z.boolean().optional(),
95
314
  tag_id: z.number().int().optional(),
96
- parent_id: z.number().int().optional().describe("Sub-contacts of one corporation."),
97
- is_active: z.boolean().optional().default(true),
98
- limit: z.number().int().min(1).max(50).optional().default(20),
99
- page: z.number().int().min(1).optional().default(1),
100
- order_by: z.string().optional().default("created"),
101
- direction: z.enum(["asc", "desc"]).optional().default("desc")
315
+ product_id: z.number().int().optional(),
316
+ lead_source_id: z.number().int().optional(),
317
+ owner_user_id: z.number().int().optional()
318
+ }
319
+ });
320
+ server.registerTool("crm_create_lead", {
321
+ title: "Create a CRM lead",
322
+ description: "Create a lead: one person at a company (flat; no sub-records). Give at least a name or a " +
323
+ "company_name. Without lead_pipeline_id/lead_stage_id it lands on the default lead " +
324
+ "pipeline's first open stage.",
325
+ inputSchema: {
326
+ company_id: companyIdSchema,
327
+ ...leadFieldParams,
328
+ lead_pipeline_id: z.number().int().optional().describe("Must be a pipeline of kind 'lead'."),
329
+ lead_stage_id: z.number().int().optional().describe("An open stage of that pipeline."),
330
+ is_active: z.boolean().optional().default(true)
102
331
  }
103
332
  }, safeHandler(async (args) => {
104
333
  const companyId = resolveCompanyId(client, args.company_id);
105
- const response = await client.get("crm/contacts/search", {
334
+ const response = await client.post("crm/leads/create", {
106
335
  company_id: companyId,
107
- search: args.search,
108
- contact_type: args.contact_type,
109
- contact_status: args.contact_status,
110
- lead_pipeline_id: args.lead_pipeline_id,
111
- lead_stage_id: args.lead_stage_id,
112
- tag_id: args.tag_id,
113
- parent_id: args.parent_id,
114
- is_active: boolParam(args.is_active),
115
- limit: args.limit,
116
- page: args.page,
117
- order_by: args.order_by,
118
- direction: args.direction
336
+ ...pick(args, [...leadKeys, "lead_pipeline_id", "lead_stage_id"]),
337
+ is_active: boolParam(args.is_active)
119
338
  });
120
- const { items, total } = extractList(response.data, "contacts");
121
- return textResult({ count: total ?? items.length, contacts: items.map(summariseContact) });
339
+ return textResult({ created: true, lead: summariseLead(response.data ?? {}) });
122
340
  }));
123
- server.registerTool("crm_get_contact", {
124
- title: "Get a CRM contact",
125
- description: "Fetch one contact (lead or customer) in full, including tags and custom fields.",
126
- inputSchema: { company_id: companyIdSchema, contact_id: z.number().int() }
341
+ server.registerTool("crm_update_lead", {
342
+ title: "Update a CRM lead",
343
+ description: "Change fields on an open lead; only the fields passed are altered. Pass lead_stage_id " +
344
+ "(with lead_pipeline_id) to move it between open stages. A converted lead is read-only. To " +
345
+ "qualify a lead use crm_convert_lead, to drop it crm_disqualify_lead.",
346
+ inputSchema: {
347
+ company_id: companyIdSchema,
348
+ lead_id: z.number().int(),
349
+ ...leadFieldParams,
350
+ lead_pipeline_id: z.number().int().optional(),
351
+ lead_stage_id: z.number().int().optional(),
352
+ lead_stage_note: z.string().optional().describe("Note recorded against the stage change."),
353
+ is_active: z.boolean().optional()
354
+ }
355
+ }, safeHandler(async (args) => {
356
+ const companyId = resolveCompanyId(client, args.company_id);
357
+ const response = await client.post("crm/leads/edit", {
358
+ company_id: companyId,
359
+ id: args.lead_id,
360
+ ...pick(args, [...leadKeys, "lead_pipeline_id", "lead_stage_id", "lead_stage_note"]),
361
+ is_active: boolParam(args.is_active)
362
+ });
363
+ return textResult({ updated: true, lead: summariseLead(response.data ?? {}) });
364
+ }));
365
+ server.registerTool("crm_lead_convert_matches", {
366
+ title: "Find conversion matches for a lead",
367
+ description: "Existing accounts and contacts that look like this lead (same email, mobile or company " +
368
+ "name), to use with account_mode/contact_mode 'match' in crm_convert_lead.",
369
+ inputSchema: { company_id: companyIdSchema, lead_id: z.number().int() }
127
370
  }, safeHandler(async (args) => {
128
371
  const companyId = resolveCompanyId(client, args.company_id);
129
- const response = await client.get(`crm/contacts/${args.contact_id}`, {
372
+ const response = await client.get(`crm/leads/${args.lead_id}/convert-matches`, {
130
373
  company_id: companyId
131
374
  });
132
375
  return textResult(response.data);
133
376
  }));
134
- server.registerTool("crm_create_contact", {
135
- title: "Create a CRM contact",
136
- description: "Create a lead or a customer. Individuals use firstname/lastname; corporations use " +
137
- "corporation_name. Set parent_id to attach as a sub-contact of an existing corporation " +
138
- "(inherits its status/pipeline/stage). Leads should include lead_pipeline_id and " +
139
- "lead_stage_id to place them on a board.",
377
+ server.registerTool("crm_convert_lead", {
378
+ title: "Convert a CRM lead",
379
+ description: "Qualify a lead: create or match an account (or none, for a consumer), create or match a " +
380
+ "contact (or none, account only), and optionally create a deal. The lead's tags, notes, " +
381
+ "attachments, products and activities move to the new records and the lead becomes " +
382
+ "read-only. This cannot be undone. Check crm_lead_convert_matches first to avoid duplicates. " +
383
+ "Creating needs the matching rights: a new account needs crm_accounts:write, a new contact " +
384
+ "crm_contacts:write, a deal crm_deals:write (plus the role's manage permission for each).",
385
+ inputSchema: {
386
+ company_id: companyIdSchema,
387
+ lead_id: z.number().int(),
388
+ account_mode: z.enum(["create", "match", "none"]),
389
+ account_id: z.number().int().optional().describe("Required when account_mode is 'match'."),
390
+ account_name: z.string().max(255).optional().describe("Overrides the lead's company_name on create."),
391
+ contact_mode: z.enum(["create", "match", "none"]).describe("Not 'none' when account_mode is 'none'."),
392
+ contact_id: z.number().int().optional().describe("Required when contact_mode is 'match'."),
393
+ create_deal: z.boolean().optional().default(false),
394
+ deal_pipeline_id: z
395
+ .number()
396
+ .int()
397
+ .optional()
398
+ .describe("Deal pipeline; defaults to the company's convert pipeline."),
399
+ deal_name: z.string().max(200).optional(),
400
+ amount: z.number().min(0).optional(),
401
+ currency_id: z.number().int().optional(),
402
+ expected_close_date: z.string().optional().describe("YYYY-MM-DD.")
403
+ }
404
+ }, safeHandler(async (args) => {
405
+ const companyId = resolveCompanyId(client, args.company_id);
406
+ const response = await client.post("crm/leads/convert", {
407
+ company_id: companyId,
408
+ id: args.lead_id,
409
+ ...pick(args, [
410
+ "account_mode",
411
+ "account_id",
412
+ "account_name",
413
+ "contact_mode",
414
+ "contact_id",
415
+ "deal_pipeline_id",
416
+ "deal_name",
417
+ "amount",
418
+ "currency_id",
419
+ "expected_close_date"
420
+ ]),
421
+ create_deal: boolParam(args.create_deal)
422
+ });
423
+ const data = response.data ?? {};
424
+ return textResult({
425
+ converted: true,
426
+ account_id: data.account_id ?? undefined,
427
+ contact_id: data.contact_id ?? undefined,
428
+ deal_id: data.deal_id ?? undefined,
429
+ lead: data.lead ? summariseLead(data.lead) : undefined
430
+ });
431
+ }));
432
+ server.registerTool("crm_disqualify_lead", {
433
+ title: "Disqualify a CRM lead",
434
+ description: "Move a lead to its pipeline's disqualified stage with a reason from " +
435
+ "crm_list_disqualify_reasons. Moving it back to an open stage with crm_update_lead re-opens it.",
140
436
  inputSchema: {
141
437
  company_id: companyIdSchema,
142
- contact_type: contactTypeSchema.optional(),
143
- parent_id: z.number().int().optional().describe("Attaches as a sub-contact; forces individual type."),
144
- firstname: z.string().optional(),
145
- lastname: z.string().optional(),
146
- corporation_name: z.string().optional(),
147
- email: z.string().optional(),
148
- phone: z.string().optional(),
149
- mobile: z.string().optional(),
150
- position: z.string().optional(),
151
- department: z.string().optional(),
152
- website: z.string().optional(),
153
- industry: z.string().optional(),
154
- employee_count: z.number().int().optional(),
438
+ lead_id: z.number().int(),
439
+ disqualify_reason_id: z.number().int(),
440
+ disqualify_note: z.string().max(1000).optional()
441
+ }
442
+ }, safeHandler(async (args) => {
443
+ const companyId = resolveCompanyId(client, args.company_id);
444
+ const lead = await client.get(`crm/leads/${args.lead_id}`, { company_id: companyId });
445
+ const pipelineId = lead.data?.lead_pipeline_id;
446
+ const stages = await client.get("crm/stages/all", {
447
+ company_id: companyId,
448
+ pipeline_id: pipelineId
449
+ });
450
+ const stage = (stages.data ?? []).find((s) => s.stage_type === "disqualified");
451
+ if (!stage) {
452
+ throw new Error(`Lead pipeline ${pipelineId} has no disqualified stage.`);
453
+ }
454
+ const response = await client.post("crm/leads/edit", {
455
+ company_id: companyId,
456
+ id: args.lead_id,
457
+ lead_pipeline_id: pipelineId,
458
+ lead_stage_id: stage.id,
459
+ disqualify_reason_id: args.disqualify_reason_id,
460
+ disqualify_note: args.disqualify_note
461
+ });
462
+ return textResult({ disqualified: true, lead: summariseLead(response.data ?? {}) });
463
+ }));
464
+ // --------------------------------------------------------------- accounts
465
+ registerRecordTools(server, client, {
466
+ kind: "account",
467
+ plural: "accounts",
468
+ summarise: summariseAccount,
469
+ searchDescription: "Search accounts (organizations). lifecycle_stage is derived from deals: prospect (no deals), " +
470
+ "opportunity (an open deal), customer (a won deal).",
471
+ getDescription: "Fetch one account in full, including its people, tags and custom fields.",
472
+ timelineDescription: "Chronological feed of activities on an account, its people and its deals.",
473
+ deleteDescription: "Soft-delete an account. Refused while it is the account of an open deal (close or move the deal first). Its contacts are kept but lose the link to it; closed deals keep it as history.",
474
+ filters: {
475
+ lifecycle_stage: lifecycleSchema.optional(),
476
+ account_type: accountTypeSchema.optional(),
477
+ tag_id: z.number().int().optional(),
478
+ product_id: z.number().int().optional(),
155
479
  lead_source_id: z.number().int().optional(),
156
- rating: z.number().int().optional(),
157
- credit_limit: z.number().optional(),
158
- payment_terms_days: z.number().int().optional(),
159
- currency: z.string().length(3).optional(),
160
- account_owner_user_id: z.number().int().optional(),
161
- lead_pipeline_id: z.number().int().optional().describe("Must be a pipeline of kind 'lead'."),
162
- lead_stage_id: z.number().int().optional(),
163
- address: z.string().optional(),
164
- city: z.string().optional(),
165
- state: z.string().optional(),
166
- postal_code: z.string().optional(),
167
- country: z.string().optional(),
168
- is_active: z.boolean().optional().default(true),
169
- notes: z.string().optional()
480
+ owner_user_id: z.number().int().optional()
481
+ }
482
+ });
483
+ server.registerTool("crm_create_account", {
484
+ title: "Create a CRM account",
485
+ description: "Create an account (an organization). Prospects normally arrive as leads and become accounts " +
486
+ "through crm_convert_lead; create one directly for an organization you already work with.",
487
+ inputSchema: {
488
+ company_id: companyIdSchema,
489
+ name: z.string().min(1).max(200),
490
+ ...accountFieldParams,
491
+ is_active: z.boolean().optional().default(true)
170
492
  }
171
493
  }, safeHandler(async (args) => {
172
494
  const companyId = resolveCompanyId(client, args.company_id);
173
- const response = await client.post("crm/contacts/create", {
495
+ const response = await client.post("crm/accounts/create", {
174
496
  company_id: companyId,
175
- contact_type: args.contact_type,
176
- parent_id: args.parent_id,
177
- firstname: args.firstname,
178
- lastname: args.lastname,
179
- corporation_name: args.corporation_name,
180
- email: args.email,
181
- phone: args.phone,
182
- mobile: args.mobile,
183
- position: args.position,
184
- department: args.department,
185
- website: args.website,
186
- industry: args.industry,
187
- employee_count: args.employee_count,
188
- lead_source_id: args.lead_source_id,
189
- rating: args.rating,
190
- credit_limit: args.credit_limit,
191
- payment_terms_days: args.payment_terms_days,
192
- currency: args.currency,
193
- account_owner_user_id: args.account_owner_user_id,
194
- lead_pipeline_id: args.lead_pipeline_id,
195
- lead_stage_id: args.lead_stage_id,
196
- address: args.address,
197
- city: args.city,
198
- state: args.state,
199
- postal_code: args.postal_code,
200
- country: args.country,
201
- is_active: boolParam(args.is_active),
202
- notes: args.notes
497
+ name: args.name,
498
+ ...pick(args, accountKeys),
499
+ is_active: boolParam(args.is_active)
203
500
  });
204
- return textResult({ created: true, contact: summariseContact(response.data ?? {}) });
501
+ return textResult({ created: true, account: summariseAccount(response.data ?? {}) });
205
502
  }));
206
- server.registerTool("crm_update_contact", {
207
- title: "Update a CRM contact",
208
- description: "Change fields on a contact. Only the fields passed are altered. To move a lead through " +
209
- "its pipeline, pass lead_pipeline_id/lead_stage_id — contact_status is derived from the " +
210
- "stage automatically, not set directly.",
503
+ server.registerTool("crm_update_account", {
504
+ title: "Update a CRM account",
505
+ description: "Change fields on an account; only the fields passed are altered. lifecycle_stage is derived.",
211
506
  inputSchema: {
212
507
  company_id: companyIdSchema,
213
- contact_id: z.number().int(),
214
- firstname: z.string().optional(),
215
- lastname: z.string().optional(),
216
- corporation_name: z.string().optional(),
217
- email: z.string().optional(),
218
- phone: z.string().optional(),
219
- mobile: z.string().optional(),
220
- position: z.string().optional(),
221
- rating: z.number().int().optional(),
222
- account_owner_user_id: z.number().int().optional(),
223
- lead_pipeline_id: z.number().int().optional(),
224
- lead_stage_id: z.number().int().optional(),
225
- lead_stage_note: z.string().optional().describe("Note recorded against the stage change."),
226
- lost_reason: z.string().optional(),
227
- is_active: z.boolean().optional(),
228
- notes: z.string().optional()
508
+ account_id: z.number().int(),
509
+ name: z.string().min(1).max(200).optional(),
510
+ ...accountFieldParams,
511
+ is_active: z.boolean().optional()
229
512
  }
230
513
  }, safeHandler(async (args) => {
231
514
  const companyId = resolveCompanyId(client, args.company_id);
232
- const response = await client.post("crm/contacts/edit", {
515
+ // the API wants the name on every edit
516
+ let name = args.name;
517
+ if (name === undefined) {
518
+ const current = await client.get(`crm/accounts/${args.account_id}`, {
519
+ company_id: companyId
520
+ });
521
+ name = current.data?.name;
522
+ }
523
+ const response = await client.post("crm/accounts/edit", {
233
524
  company_id: companyId,
234
- id: args.contact_id,
235
- firstname: args.firstname,
236
- lastname: args.lastname,
237
- corporation_name: args.corporation_name,
238
- email: args.email,
239
- phone: args.phone,
240
- mobile: args.mobile,
241
- position: args.position,
242
- rating: args.rating,
243
- account_owner_user_id: args.account_owner_user_id,
244
- lead_pipeline_id: args.lead_pipeline_id,
245
- lead_stage_id: args.lead_stage_id,
246
- lead_stage_note: args.lead_stage_note,
247
- lost_reason: args.lost_reason,
248
- is_active: args.is_active === undefined ? undefined : boolParam(args.is_active),
249
- notes: args.notes
525
+ id: args.account_id,
526
+ name,
527
+ ...pick(args, accountKeys),
528
+ is_active: boolParam(args.is_active)
250
529
  });
251
- return textResult({ updated: true, contact: summariseContact(response.data ?? {}) });
530
+ return textResult({ updated: true, account: summariseAccount(response.data ?? {}) });
252
531
  }));
253
- server.registerTool("crm_delete_contact", {
254
- title: "Delete a CRM contact",
255
- description: "Soft-delete a contact. Its sub-contacts are hidden along with it.",
256
- inputSchema: { company_id: companyIdSchema, contact_id: z.number().int() }
532
+ // --------------------------------------------------------------- contacts
533
+ registerRecordTools(server, client, {
534
+ kind: "contact",
535
+ plural: "contacts",
536
+ summarise: summariseContact,
537
+ searchDescription: "Search contacts (people). account_id lists the people linked to one account (primary or " +
538
+ "additional). lifecycle_stage is derived from deals.",
539
+ getDescription: "Fetch one contact in full, including linked accounts, tags and custom fields.",
540
+ timelineDescription: "Chronological feed of activities on a contact and on its deals.",
541
+ deleteDescription: "Soft-delete a contact. Refused while they are the primary contact of an open deal (close or move the deal first); closed deals keep them as history.",
542
+ filters: {
543
+ lifecycle_stage: lifecycleSchema.optional(),
544
+ account_id: z.number().int().optional(),
545
+ tag_id: z.number().int().optional(),
546
+ product_id: z.number().int().optional(),
547
+ lead_source_id: z.number().int().optional(),
548
+ owner_user_id: z.number().int().optional()
549
+ }
550
+ });
551
+ server.registerTool("crm_create_contact", {
552
+ title: "Create a CRM contact",
553
+ description: "Create a contact (a person), optionally linked to a primary account. Give at least a first " +
554
+ "or last name. A contact without an account is a consumer (B2C) customer.",
555
+ inputSchema: {
556
+ company_id: companyIdSchema,
557
+ account_id: z.number().int().optional().describe("Primary account."),
558
+ ...contactFieldParams,
559
+ is_active: z.boolean().optional().default(true)
560
+ }
257
561
  }, safeHandler(async (args) => {
258
562
  const companyId = resolveCompanyId(client, args.company_id);
259
- await client.post(`crm/contacts/delete/${args.contact_id}`, { company_id: companyId });
260
- return textResult({ deleted: true, contact_id: args.contact_id });
563
+ const response = await client.post("crm/contacts/create", {
564
+ company_id: companyId,
565
+ ...pick(args, contactKeys),
566
+ is_active: boolParam(args.is_active)
567
+ });
568
+ return textResult({ created: true, contact: summariseContact(response.data ?? {}) });
261
569
  }));
262
- server.registerTool("crm_contact_timeline", {
263
- title: "Get a contact's activity timeline",
264
- description: "Chronological feed of activities on a contact and on its deals.",
570
+ server.registerTool("crm_update_contact", {
571
+ title: "Update a CRM contact",
572
+ description: "Change fields on a contact; only the fields passed are altered. account_id changes the " +
573
+ "primary account. lifecycle_stage is derived.",
265
574
  inputSchema: {
266
575
  company_id: companyIdSchema,
267
576
  contact_id: z.number().int(),
268
- limit: z.number().int().min(1).max(100).optional().default(20),
269
- page: z.number().int().min(1).optional().default(1)
577
+ account_id: z.number().int().optional().describe("New primary account."),
578
+ ...contactFieldParams,
579
+ is_active: z.boolean().optional()
270
580
  }
271
581
  }, safeHandler(async (args) => {
272
582
  const companyId = resolveCompanyId(client, args.company_id);
273
- const response = await client.get(`crm/contacts/${args.contact_id}/timeline`, { company_id: companyId, limit: args.limit, page: args.page });
274
- const { items, total } = extractList(response.data, "activities");
275
- return textResult({ count: total ?? items.length, activities: items.map(summariseActivity) });
583
+ const response = await client.post("crm/contacts/edit", {
584
+ company_id: companyId,
585
+ id: args.contact_id,
586
+ ...pick(args, contactKeys),
587
+ is_active: boolParam(args.is_active)
588
+ });
589
+ return textResult({ updated: true, contact: summariseContact(response.data ?? {}) });
276
590
  }));
277
591
  // ------------------------------------------------------------------ deals
278
592
  server.registerTool("crm_search_deals", {
279
593
  title: "Search CRM deals",
280
- description: "Search deals, optionally by pipeline, stage, contact, or lifecycle status.",
594
+ description: "Search deals, optionally by account, primary contact, pipeline, stage, or status.",
281
595
  inputSchema: {
282
596
  company_id: companyIdSchema,
283
597
  search: z.string().optional(),
284
- contact_id: z.number().int().optional(),
598
+ account_id: z.number().int().optional(),
599
+ contact_id: z.number().int().optional().describe("The deal's primary contact."),
285
600
  pipeline_id: z.number().int().optional(),
286
601
  stage_id: z.number().int().optional(),
287
602
  assigned_to_user_id: z.number().int().optional(),
@@ -296,6 +611,7 @@ export function registerCrmTools(server, client) {
296
611
  const response = await client.get("crm/deals/search", {
297
612
  company_id: companyId,
298
613
  search: args.search,
614
+ account_id: args.account_id,
299
615
  contact_id: args.contact_id,
300
616
  pipeline_id: args.pipeline_id,
301
617
  stage_id: args.stage_id,
@@ -322,18 +638,20 @@ export function registerCrmTools(server, client) {
322
638
  }));
323
639
  server.registerTool("crm_create_deal", {
324
640
  title: "Create a CRM deal",
325
- description: "Create a deal on a pipeline/stage. Resolve pipeline_id and stage_id with " +
326
- "crm_list_pipelines and crm_list_stages, and contact_id with crm_search_contacts — or " +
327
- "with run_company_sql over v_ai_crm_pipelines / v_ai_crm_stages / v_ai_contacts when " +
328
- "those tools are not registered.",
641
+ description: "Create a deal on a pipeline/stage for an account and/or a primary contact (at least one; " +
642
+ "when both are given the contact must be linked to the account). A deal never belongs to a " +
643
+ "lead: convert the lead with crm_convert_lead (create_deal) instead. Resolve ids with " +
644
+ "crm_list_pipelines, crm_list_stages, crm_search_accounts and crm_search_contacts — or with " +
645
+ "run_company_sql over v_ai_crm_pipelines / v_ai_crm_stages / v_ai_crm_accounts / " +
646
+ "v_ai_crm_contacts when those tools are not registered.",
329
647
  inputSchema: {
330
648
  company_id: companyIdSchema,
331
649
  deal_name: z.string().min(1).max(200),
332
- contact_id: z.number().int(),
650
+ account_id: z.number().int().optional(),
651
+ primary_contact_id: z.number().int().optional(),
333
652
  pipeline_id: z.number().int().describe("Must be a pipeline of kind 'deal'."),
334
653
  stage_id: z.number().int(),
335
654
  assigned_to_user_id: z.number().int(),
336
- primary_contact_person_id: z.number().int().optional(),
337
655
  amount: z.number().optional().default(0),
338
656
  currency_id: z.number().int().optional(),
339
657
  expected_close_date: z.string().optional(),
@@ -344,15 +662,18 @@ export function registerCrmTools(server, client) {
344
662
  competitors: z.array(z.string()).optional()
345
663
  }
346
664
  }, safeHandler(async (args) => {
665
+ if (args.account_id === undefined && args.primary_contact_id === undefined) {
666
+ throw new Error("A deal needs account_id or primary_contact_id.");
667
+ }
347
668
  const companyId = resolveCompanyId(client, args.company_id);
348
669
  const response = await client.post("crm/deals/create", {
349
670
  company_id: companyId,
350
671
  deal_name: args.deal_name,
351
- contact_id: args.contact_id,
672
+ account_id: args.account_id,
673
+ primary_contact_id: args.primary_contact_id,
352
674
  pipeline_id: args.pipeline_id,
353
675
  stage_id: args.stage_id,
354
676
  assigned_to_user_id: args.assigned_to_user_id,
355
- primary_contact_person_id: args.primary_contact_person_id,
356
677
  amount: args.amount,
357
678
  currency_id: args.currency_id,
358
679
  expected_close_date: args.expected_close_date,
@@ -369,12 +690,13 @@ export function registerCrmTools(server, client) {
369
690
  description: "Change fields on a deal. Only the fields passed are altered — the deal is read first and " +
370
691
  "unmentioned fields keep their current values (the underlying API replaces the whole row, " +
371
692
  "so this tool merges for you). Moving into a won/lost stage auto-fills actual_close_date " +
372
- "unless you pass one.",
693
+ "unless you pass one. Winning a deal makes its account and contact customers.",
373
694
  inputSchema: {
374
695
  company_id: companyIdSchema,
375
696
  deal_id: z.number().int(),
376
697
  deal_name: z.string().min(1).max(200).optional(),
377
- contact_id: z.number().int().optional(),
698
+ account_id: z.number().int().optional(),
699
+ primary_contact_id: z.number().int().optional(),
378
700
  pipeline_id: z.number().int().optional(),
379
701
  stage_id: z.number().int().optional(),
380
702
  assigned_to_user_id: z.number().int().optional(),
@@ -400,7 +722,9 @@ export function registerCrmTools(server, client) {
400
722
  company_id: companyId,
401
723
  id: args.deal_id,
402
724
  deal_name: args.deal_name ?? deal.deal_name,
403
- contact_id: args.contact_id ?? deal.contact_id,
725
+ // parties: an omitted key keeps the stored value server-side
726
+ account_id: args.account_id,
727
+ primary_contact_id: args.primary_contact_id,
404
728
  pipeline_id: args.pipeline_id ?? deal.pipeline_id,
405
729
  stage_id: args.stage_id ?? deal.stage_id,
406
730
  assigned_to_user_id: args.assigned_to_user_id ?? deal.assigned_to_user_id,
@@ -501,14 +825,16 @@ export function registerCrmTools(server, client) {
501
825
  // ------------------------------------------------------------- activities
502
826
  server.registerTool("crm_search_activities", {
503
827
  title: "Search CRM activities",
504
- description: "Search calls, emails, meetings, tasks and notes logged against contacts or deals.",
828
+ description: "Search calls, emails, meetings, tasks and notes. who_type/who_id filter by the person " +
829
+ "(Lead or Contact), what_type/what_id by the Account or Deal.",
505
830
  inputSchema: {
506
831
  company_id: companyIdSchema,
507
832
  search: z.string().optional(),
508
833
  activity_type: z.enum(["call", "email", "meeting", "task", "note"]).optional(),
509
- related_to_type: relatedToTypeSchema.optional(),
510
- related_to_id: z.number().int().optional(),
511
- contact_id: z.number().int().optional(),
834
+ who_type: whoTypeSchema.optional(),
835
+ who_id: z.number().int().optional(),
836
+ what_type: whatTypeSchema.optional(),
837
+ what_id: z.number().int().optional(),
512
838
  status: z.enum(["pending", "completed", "cancelled"]).optional(),
513
839
  assigned_to_user_id: z.number().int().optional(),
514
840
  priority: z.enum(["low", "medium", "high"]).optional(),
@@ -522,9 +848,10 @@ export function registerCrmTools(server, client) {
522
848
  company_id: companyId,
523
849
  search: args.search,
524
850
  activity_type: args.activity_type,
525
- related_to_type: args.related_to_type,
526
- related_to_id: args.related_to_id,
527
- contact_id: args.contact_id,
851
+ who_type: args.who_type,
852
+ who_id: args.who_id,
853
+ what_type: args.what_type,
854
+ what_id: args.what_id,
528
855
  status: args.status,
529
856
  assigned_to_user_id: args.assigned_to_user_id,
530
857
  priority: args.priority,
@@ -537,13 +864,17 @@ export function registerCrmTools(server, client) {
537
864
  }));
538
865
  server.registerTool("crm_create_activity", {
539
866
  title: "Create a CRM activity",
540
- description: "Log a call, email, meeting, task, or note against a contact or a deal.",
867
+ description: "Log a call, email, meeting, task, or note. Link a Who (Lead or Contact) and/or a What " +
868
+ "(Account or Deal) — at least one. A converted lead takes no new activities; use its contact.",
541
869
  inputSchema: {
542
870
  company_id: companyIdSchema,
543
871
  activity_type: z.enum(["call", "email", "meeting", "task", "note"]),
544
872
  subject: z.string().min(1).max(200),
545
- related_to_type: relatedToTypeSchema,
546
- related_to_id: z.number().int(),
873
+ who_type: whoTypeSchema.optional(),
874
+ who_id: z.number().int().optional(),
875
+ what_type: whatTypeSchema.optional(),
876
+ what_id: z.number().int().optional(),
877
+ description: z.string().optional(),
547
878
  assigned_to_user_id: z.number().int().optional(),
548
879
  due_date: z.string().optional(),
549
880
  reminder_at: z.string().optional(),
@@ -554,13 +885,19 @@ export function registerCrmTools(server, client) {
554
885
  outcome: z.string().optional()
555
886
  }
556
887
  }, safeHandler(async (args) => {
888
+ if (!(args.who_type && args.who_id) && !(args.what_type && args.what_id)) {
889
+ throw new Error("An activity needs who_type + who_id or what_type + what_id.");
890
+ }
557
891
  const companyId = resolveCompanyId(client, args.company_id);
558
892
  const response = await client.post("crm/activities/create", {
559
893
  company_id: companyId,
560
894
  activity_type: args.activity_type,
561
895
  subject: args.subject,
562
- related_to_type: args.related_to_type,
563
- related_to_id: args.related_to_id,
896
+ who_type: args.who_type,
897
+ who_id: args.who_id,
898
+ what_type: args.what_type,
899
+ what_id: args.what_id,
900
+ description: args.description,
564
901
  assigned_to_user_id: args.assigned_to_user_id,
565
902
  due_date: args.due_date,
566
903
  reminder_at: args.reminder_at,
@@ -603,7 +940,8 @@ export function registerCrmTools(server, client) {
603
940
  // ------------------------------------------------------------- dashboard
604
941
  server.registerTool("crm_dashboard_summary", {
605
942
  title: "CRM dashboard summary",
606
- description: "Win/loss rates, forecast, lead sources and activity stats over a date range.",
943
+ description: "Win/loss rates, forecast, lead funnel (created / converted / disqualified), customers, lead " +
944
+ "sources and activity stats over a date range.",
607
945
  inputSchema: {
608
946
  company_id: companyIdSchema,
609
947
  from: z.string().optional().describe("YYYY-MM-DD, defaults to 30 days ago."),