@initiativesolutions/crm-mcp-server 0.0.0-stage → 0.5.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 +192 -2
- package/dist/config.d.ts +36 -0
- package/dist/config.js +125 -0
- package/dist/constants.d.ts +51 -0
- package/dist/constants.js +68 -0
- package/dist/errors.d.ts +60 -0
- package/dist/errors.js +399 -0
- package/dist/field-sets.d.ts +37 -0
- package/dist/field-sets.js +97 -0
- package/dist/fold.d.ts +2 -0
- package/dist/fold.js +5 -0
- package/dist/guides.d.ts +37 -0
- package/dist/guides.js +80 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +28 -0
- package/dist/render.d.ts +53 -0
- package/dist/render.js +237 -0
- package/dist/server.d.ts +25 -0
- package/dist/server.js +89 -0
- package/dist/services/api-client.d.ts +42 -0
- package/dist/services/api-client.js +40 -0
- package/dist/services/path.d.ts +9 -0
- package/dist/services/path.js +33 -0
- package/dist/services/query.d.ts +7 -0
- package/dist/services/query.js +56 -0
- package/dist/services/transport.d.ts +48 -0
- package/dist/services/transport.js +264 -0
- package/dist/services/upload-source.d.ts +26 -0
- package/dist/services/upload-source.js +206 -0
- package/dist/services/write-client.d.ts +34 -0
- package/dist/services/write-client.js +57 -0
- package/dist/token-source.d.ts +21 -0
- package/dist/token-source.js +11 -0
- package/dist/tools/deletes.d.ts +3 -0
- package/dist/tools/deletes.js +54 -0
- package/dist/tools/discovery.d.ts +4 -0
- package/dist/tools/discovery.js +165 -0
- package/dist/tools/help.d.ts +3 -0
- package/dist/tools/help.js +96 -0
- package/dist/tools/lines.d.ts +33 -0
- package/dist/tools/lines.js +285 -0
- package/dist/tools/records.d.ts +14 -0
- package/dist/tools/records.js +141 -0
- package/dist/tools/relations.d.ts +4 -0
- package/dist/tools/relations.js +97 -0
- package/dist/tools/schemas.d.ts +76 -0
- package/dist/tools/schemas.js +59 -0
- package/dist/tools/sync.d.ts +4 -0
- package/dist/tools/sync.js +107 -0
- package/dist/tools/writes.d.ts +4 -0
- package/dist/tools/writes.js +353 -0
- package/dist/validation.d.ts +15 -0
- package/dist/validation.js +80 -0
- package/dist/write-wiring.d.ts +4 -0
- package/dist/write-wiring.js +5 -0
- package/docs/partners/en/install.md +206 -0
- package/docs/partners/fr/install.md +206 -0
- package/guides/en/best-practices.md +134 -0
- package/guides/en/converting-leads.md +189 -0
- package/guides/en/fields-and-formats.md +365 -0
- package/guides/en/inventory-documents.md +252 -0
- package/guides/en/linking-records.md +266 -0
- package/guides/en/price-books.md +233 -0
- package/guides/en/querying-records.md +197 -0
- package/guides/en/syncing-data.md +276 -0
- package/guides/en/uploading-documents.md +194 -0
- package/guides/en/writing-records.md +239 -0
- package/guides/fr/best-practices.md +134 -0
- package/guides/fr/converting-leads.md +189 -0
- package/guides/fr/fields-and-formats.md +365 -0
- package/guides/fr/inventory-documents.md +252 -0
- package/guides/fr/linking-records.md +266 -0
- package/guides/fr/price-books.md +233 -0
- package/guides/fr/querying-records.md +197 -0
- package/guides/fr/syncing-data.md +277 -0
- package/guides/fr/uploading-documents.md +194 -0
- package/guides/fr/writing-records.md +239 -0
- package/guides/manifest.json +174 -0
- package/package.json +54 -4
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { InitiativeApiError, toToolResult } from '../errors.js';
|
|
3
|
+
import { renderWriteResult } from '../render.js';
|
|
4
|
+
import { idSegment, moduleSegment } from '../services/path.js';
|
|
5
|
+
import { resolveUploadSource } from '../services/upload-source.js';
|
|
6
|
+
import { MAX_LINES_PER_CALL } from '../constants.js';
|
|
7
|
+
import { DATA_ARG, GROUP_ARG, ID_EMPTY, LINE_ARG, MODULE_ARG, WRITE_ADD_ANNOTATIONS, WRITE_REPLACE_ANNOTATIONS, WRITE_UPDATE_ANNOTATIONS, } from './schemas.js';
|
|
8
|
+
/**
|
|
9
|
+
* Keys of an ordinary write that would replace the lines of a document. Lines go through
|
|
10
|
+
* initiative_set_line_items only, so the one replace-everything path has one safeguard.
|
|
11
|
+
*/
|
|
12
|
+
const LINE_KEYS = ['line_items', 'group'];
|
|
13
|
+
function refuseLines(data) {
|
|
14
|
+
const found = LINE_KEYS.filter((key) => key in data);
|
|
15
|
+
if (found.length === 0)
|
|
16
|
+
return;
|
|
17
|
+
throw new InitiativeApiError({
|
|
18
|
+
status: null,
|
|
19
|
+
requestSent: false,
|
|
20
|
+
code: 'LINES_NOT_ACCEPTED',
|
|
21
|
+
message: `${found.join(' and ')} cannot be written here. A write of lines replaces the whole set with no merge.`,
|
|
22
|
+
requestId: null,
|
|
23
|
+
retryable: false,
|
|
24
|
+
nextStep: 'No request was made. Remove it from data and use initiative_set_line_items to read and then set the lines of a quote, invoice or order.',
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
/** A create or an update with no field at all: nothing to write, so nothing is sent. */
|
|
28
|
+
function refuseEmpty(data, verb) {
|
|
29
|
+
if (Object.keys(data).length > 0)
|
|
30
|
+
return;
|
|
31
|
+
throw new InitiativeApiError({
|
|
32
|
+
status: null,
|
|
33
|
+
requestSent: false,
|
|
34
|
+
code: 'INVALID_ARGUMENT',
|
|
35
|
+
message: verb === 'update' ? 'data is empty, so there is nothing to change.' : 'data is empty, so there is nothing to create.',
|
|
36
|
+
requestId: null,
|
|
37
|
+
retryable: false,
|
|
38
|
+
nextStep: 'No request was made. Put the field values in data, with the field names from initiative_describe_module' +
|
|
39
|
+
(verb === 'create' ? ' (a quote, invoice or order also needs line_items).' : '.'),
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* A create has no existing lines to destroy, so line_items is accepted on create: the API refuses a
|
|
44
|
+
* quote, invoice or order without at least one line, so the lines must arrive with the record.
|
|
45
|
+
* They are checked like the lines of initiative_set_line_items, and the checked lines are what is
|
|
46
|
+
* sent: keys a line cannot set, and computed parts of group such as totals, are dropped. group
|
|
47
|
+
* travels only with lines.
|
|
48
|
+
*/
|
|
49
|
+
function checkCreateLines(data) {
|
|
50
|
+
if (!('line_items' in data)) {
|
|
51
|
+
if ('group' in data) {
|
|
52
|
+
throw new InitiativeApiError({
|
|
53
|
+
status: null,
|
|
54
|
+
requestSent: false,
|
|
55
|
+
code: 'LINES_NOT_ACCEPTED',
|
|
56
|
+
message: 'group is sent only together with line_items.',
|
|
57
|
+
requestId: null,
|
|
58
|
+
retryable: false,
|
|
59
|
+
nextStep: 'No request was made. Add line_items, or remove group.',
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
return data;
|
|
63
|
+
}
|
|
64
|
+
const parsed = z.array(LINE_ARG).min(1).max(MAX_LINES_PER_CALL).safeParse(data.line_items);
|
|
65
|
+
if (!parsed.success) {
|
|
66
|
+
throw new InitiativeApiError({
|
|
67
|
+
status: null,
|
|
68
|
+
requestSent: false,
|
|
69
|
+
code: 'INVALID_ARGUMENT',
|
|
70
|
+
message: `line_items is not valid: ${parsed.error.issues[0]?.message ?? 'wrong shape'}.`,
|
|
71
|
+
requestId: null,
|
|
72
|
+
retryable: false,
|
|
73
|
+
nextStep: `No request was made. Send 1 to ${MAX_LINES_PER_CALL} lines, each with exactly one of product_id or service_id and a quantity above 0.`,
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
const out = { ...data, line_items: parsed.data };
|
|
77
|
+
if ('group' in data) {
|
|
78
|
+
const group = GROUP_ARG.safeParse(data.group);
|
|
79
|
+
if (!group.success) {
|
|
80
|
+
throw new InitiativeApiError({
|
|
81
|
+
status: null,
|
|
82
|
+
requestSent: false,
|
|
83
|
+
code: 'INVALID_ARGUMENT',
|
|
84
|
+
message: `group is not valid: ${group.error.issues[0]?.message ?? 'wrong shape'}.`,
|
|
85
|
+
requestId: null,
|
|
86
|
+
retryable: false,
|
|
87
|
+
nextStep: 'No request was made. group takes only shipping.cost, global_discount.percent or .amount, and adjustment, as numbers.',
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
out.group = group.data;
|
|
91
|
+
}
|
|
92
|
+
return out;
|
|
93
|
+
}
|
|
94
|
+
/** The record of a write answer, or undefined when the CRM returned none (an empty 2xx, or only meta). */
|
|
95
|
+
function recordOf(body) {
|
|
96
|
+
const data = body?.data;
|
|
97
|
+
if (typeof data !== 'object' || data === null)
|
|
98
|
+
return undefined;
|
|
99
|
+
const { id, type, attributes } = data;
|
|
100
|
+
if (!((typeof id === 'string' && id !== '') || typeof id === 'number'))
|
|
101
|
+
return undefined;
|
|
102
|
+
return {
|
|
103
|
+
id: String(id),
|
|
104
|
+
type: typeof type === 'string' ? type : '',
|
|
105
|
+
attributes: typeof attributes === 'object' && attributes !== null ? attributes : {},
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
/** The answer when the CRM accepted a write but returned no record to show. Not an error. */
|
|
109
|
+
function acceptedWithoutRecord(status, requestId) {
|
|
110
|
+
return {
|
|
111
|
+
content: [
|
|
112
|
+
{
|
|
113
|
+
type: 'text',
|
|
114
|
+
text: `The CRM accepted the change (HTTP ${status}, request id ${requestId ?? 'none'}) but returned no record. ` +
|
|
115
|
+
'It may have been applied. Read before you try again.',
|
|
116
|
+
},
|
|
117
|
+
],
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
export function registerWriteTools(server, writeClient, config) {
|
|
121
|
+
server.registerTool('initiative_create_record', {
|
|
122
|
+
description: 'Create a record. data holds field names from initiative_describe_module; reference fields take a plain id. ' +
|
|
123
|
+
'A quote, invoice or order needs line_items now; change lines later with initiative_set_line_items.',
|
|
124
|
+
inputSchema: z.object({ module: MODULE_ARG, data: DATA_ARG }),
|
|
125
|
+
annotations: WRITE_ADD_ANNOTATIONS,
|
|
126
|
+
}, async (args) => {
|
|
127
|
+
try {
|
|
128
|
+
refuseEmpty(args.data, 'create');
|
|
129
|
+
const data = checkCreateLines(args.data);
|
|
130
|
+
const { body, status, requestId } = await writeClient.create(args.module, data, {
|
|
131
|
+
context: { module: args.module },
|
|
132
|
+
});
|
|
133
|
+
const record = recordOf(body);
|
|
134
|
+
if (record === undefined)
|
|
135
|
+
return acceptedWithoutRecord(status, requestId);
|
|
136
|
+
const text = renderWriteResult('Created', args.module, record, Object.keys(data), {
|
|
137
|
+
maxChars: config.maxResponseChars,
|
|
138
|
+
});
|
|
139
|
+
return { content: [{ type: 'text', text }] };
|
|
140
|
+
}
|
|
141
|
+
catch (error) {
|
|
142
|
+
return toToolResult(error);
|
|
143
|
+
}
|
|
144
|
+
});
|
|
145
|
+
server.registerTool('initiative_update_record', {
|
|
146
|
+
description: 'Change only the given fields of a record; other fields keep their values. Invoices change only while they are drafts.',
|
|
147
|
+
inputSchema: z.object({
|
|
148
|
+
module: MODULE_ARG,
|
|
149
|
+
id: z.string().min(1, ID_EMPTY).describe('Record id.'),
|
|
150
|
+
data: DATA_ARG,
|
|
151
|
+
}),
|
|
152
|
+
annotations: WRITE_UPDATE_ANNOTATIONS,
|
|
153
|
+
}, async (args) => {
|
|
154
|
+
try {
|
|
155
|
+
refuseLines(args.data);
|
|
156
|
+
refuseEmpty(args.data, 'update');
|
|
157
|
+
const { body, status, requestId } = await writeClient.update(args.module, args.id, args.data, {
|
|
158
|
+
context: { module: args.module },
|
|
159
|
+
});
|
|
160
|
+
const record = recordOf(body);
|
|
161
|
+
if (record === undefined)
|
|
162
|
+
return acceptedWithoutRecord(status, requestId);
|
|
163
|
+
const text = renderWriteResult('Updated', args.module, record, Object.keys(args.data), {
|
|
164
|
+
maxChars: config.maxResponseChars,
|
|
165
|
+
});
|
|
166
|
+
return { content: [{ type: 'text', text }] };
|
|
167
|
+
}
|
|
168
|
+
catch (error) {
|
|
169
|
+
return toToolResult(error);
|
|
170
|
+
}
|
|
171
|
+
});
|
|
172
|
+
registerLinkAndCommentTools(server, writeClient, config);
|
|
173
|
+
}
|
|
174
|
+
const COMMENT_TARGETS = ['leads', 'accounts', 'contacts', 'potentials', 'helpdesk'];
|
|
175
|
+
/**
|
|
176
|
+
* Links the CRM answers 201 for but does not store (guide "Link records", step 3): a follow-up
|
|
177
|
+
* read of the relation is empty. Keyed "module>related_module".
|
|
178
|
+
*/
|
|
179
|
+
const NOT_STORED_LINKS = new Set(['accounts>products', 'contacts>products']);
|
|
180
|
+
function registerLinkAndCommentTools(server, writeClient, config) {
|
|
181
|
+
server.registerTool('initiative_link_records', {
|
|
182
|
+
description: 'Link two records, e.g. a product to a price book with listprice. initiative_list_related_modules shows which links can be created.',
|
|
183
|
+
inputSchema: z.object({
|
|
184
|
+
module: MODULE_ARG,
|
|
185
|
+
id: z.string().min(1, ID_EMPTY).describe('Id of the record to link from.'),
|
|
186
|
+
related_module: z.string().describe('Module slug of the record to link to. See initiative_list_related_modules.'),
|
|
187
|
+
related_id: z.string().min(1, ID_EMPTY).describe('Id of the record to link to.'),
|
|
188
|
+
attributes: DATA_ARG.optional().describe('Data carried by the link itself, e.g. listprice for a price book. Most links carry none.'),
|
|
189
|
+
}),
|
|
190
|
+
annotations: WRITE_ADD_ANNOTATIONS,
|
|
191
|
+
}, async (args) => {
|
|
192
|
+
try {
|
|
193
|
+
const { status } = await writeClient.link(args.module, args.id, args.related_module, args.related_id, args.attributes, { context: { module: args.module } });
|
|
194
|
+
const pair = `${args.module} ${args.id} and ${args.related_module} ${args.related_id}`;
|
|
195
|
+
const notStored = NOT_STORED_LINKS.has(`${args.module}>${args.related_module}`);
|
|
196
|
+
const lines = [
|
|
197
|
+
status === 200 && args.attributes !== undefined
|
|
198
|
+
? `Updated the link's data for ${pair}: ${Object.keys(args.attributes).join(', ')}.`
|
|
199
|
+
: notStored
|
|
200
|
+
? `The CRM answered success for linking ${args.module} ${args.id} to ${args.related_module} ${args.related_id}, ` +
|
|
201
|
+
`but it is known to accept a link from ${args.module} to ${args.related_module} without storing it.`
|
|
202
|
+
: `Linked ${args.module} ${args.id} to ${args.related_module} ${args.related_id}.`,
|
|
203
|
+
`Confirm it with initiative_list_related_records ${args.module} ${args.id} ${args.related_module}.`,
|
|
204
|
+
];
|
|
205
|
+
return { content: [{ type: 'text', text: lines.join('\n') }] };
|
|
206
|
+
}
|
|
207
|
+
catch (error) {
|
|
208
|
+
return toToolResult(error);
|
|
209
|
+
}
|
|
210
|
+
});
|
|
211
|
+
server.registerTool('initiative_add_comment', {
|
|
212
|
+
description: 'Add a note to a lead, account, contact, opportunity or ticket. reply_to threads it under a note of the same record.',
|
|
213
|
+
inputSchema: z.object({
|
|
214
|
+
related_module: z.enum(COMMENT_TARGETS).describe('Module slug of the record that gets the note.'),
|
|
215
|
+
related_id: z.string().min(1, ID_EMPTY).describe('Id of the record that gets the note.'),
|
|
216
|
+
text: z.string().min(1).describe('The note text.'),
|
|
217
|
+
reply_to: z.string().min(1, ID_EMPTY).optional().describe('Id of a note on the same record to reply to.'),
|
|
218
|
+
}),
|
|
219
|
+
annotations: WRITE_ADD_ANNOTATIONS,
|
|
220
|
+
}, async (args) => {
|
|
221
|
+
try {
|
|
222
|
+
const { body, status, requestId } = await writeClient.createComment({
|
|
223
|
+
commentcontent: args.text,
|
|
224
|
+
related_to: { id: args.related_id, type: args.related_module },
|
|
225
|
+
...(args.reply_to === undefined ? {} : { parent_comments: args.reply_to }),
|
|
226
|
+
});
|
|
227
|
+
const record = recordOf(body);
|
|
228
|
+
if (record === undefined)
|
|
229
|
+
return acceptedWithoutRecord(status, requestId);
|
|
230
|
+
const reply = args.reply_to === undefined ? '' : `, as a reply to ${args.reply_to}`;
|
|
231
|
+
return {
|
|
232
|
+
content: [
|
|
233
|
+
{
|
|
234
|
+
type: 'text',
|
|
235
|
+
text: `Added comment ${record.id} to ${args.related_module} ${args.related_id}${reply}.`,
|
|
236
|
+
},
|
|
237
|
+
],
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
catch (error) {
|
|
241
|
+
return toToolResult(error);
|
|
242
|
+
}
|
|
243
|
+
});
|
|
244
|
+
server.registerTool('initiative_upload_document', {
|
|
245
|
+
description: 'Upload a file as a document (a file path works only inside the configured upload folder; or base64 content with a filename), optionally attached to a record.',
|
|
246
|
+
inputSchema: z.object({
|
|
247
|
+
title: z.string().min(1).describe('Title of the document.'),
|
|
248
|
+
file_path: z.string().min(1).optional().describe('Absolute path of a file inside the upload folder. Not with content_base64.'),
|
|
249
|
+
content_base64: z.string().optional().describe('The file content as base64 text. Needs filename. Not with file_path.'),
|
|
250
|
+
filename: z.string().min(1).optional().describe('File name for content_base64, e.g. report.pdf.'),
|
|
251
|
+
folder_id: z.string().min(1, ID_EMPTY).optional().describe('Folder id. initiative_lookup_reference_data lists them.'),
|
|
252
|
+
attach_to: z
|
|
253
|
+
.object({ module: MODULE_ARG, id: z.string().min(1, ID_EMPTY).describe('Record id.') })
|
|
254
|
+
.optional()
|
|
255
|
+
.describe('A record to attach the document to.'),
|
|
256
|
+
}),
|
|
257
|
+
annotations: WRITE_ADD_ANNOTATIONS,
|
|
258
|
+
}, async (args) => {
|
|
259
|
+
try {
|
|
260
|
+
// Check the arguments that need no file first, so a bad one never costs a file read.
|
|
261
|
+
const attach = args.attach_to;
|
|
262
|
+
if (attach !== undefined) {
|
|
263
|
+
moduleSegment(attach.module);
|
|
264
|
+
idSegment(attach.id);
|
|
265
|
+
}
|
|
266
|
+
const file = await resolveUploadSource(args, config.uploadDir, config.uploadDirAsGiven ?? null);
|
|
267
|
+
const { body, status, requestId } = await writeClient.uploadDocument({
|
|
268
|
+
notes_title: args.title,
|
|
269
|
+
...(args.folder_id === undefined ? {} : { folderid: args.folder_id }),
|
|
270
|
+
...(attach === undefined ? {} : { related_to: { id: attach.id, type: attach.module } }),
|
|
271
|
+
}, file, { context: { module: 'documents' } });
|
|
272
|
+
const record = recordOf(body);
|
|
273
|
+
if (record === undefined)
|
|
274
|
+
return acceptedWithoutRecord(status, requestId);
|
|
275
|
+
const attrs = record.attributes;
|
|
276
|
+
const name = typeof attrs.filename === 'string' ? attrs.filename : file.name;
|
|
277
|
+
const size = typeof attrs.filesize === 'number' ? attrs.filesize : file.bytes.length;
|
|
278
|
+
const lines = [`Uploaded document ${record.id}: ${name} (${size} bytes).`];
|
|
279
|
+
if (attach !== undefined) {
|
|
280
|
+
const echoed = body?.meta?.related_to;
|
|
281
|
+
lines.push(echoed?.id !== undefined && echoed.type !== undefined
|
|
282
|
+
? `Attached to ${String(echoed.type)} ${String(echoed.id)}.`
|
|
283
|
+
: 'The document was created, but the CRM did not confirm the attachment. Check it with initiative_list_related_records.');
|
|
284
|
+
}
|
|
285
|
+
return { content: [{ type: 'text', text: lines.join('\n') }] };
|
|
286
|
+
}
|
|
287
|
+
catch (error) {
|
|
288
|
+
return toToolResult(error);
|
|
289
|
+
}
|
|
290
|
+
});
|
|
291
|
+
server.registerTool('initiative_convert_lead', {
|
|
292
|
+
description: 'Convert a lead into a contact and an account, and optionally an opportunity. There is no undo.',
|
|
293
|
+
inputSchema: z.object({
|
|
294
|
+
lead_id: z.string().min(1, ID_EMPTY).describe('Id of the lead to convert.'),
|
|
295
|
+
contact: DATA_ARG.optional().describe('Field values for the new contact. Omit to use what the lead already has.'),
|
|
296
|
+
account: DATA_ARG.optional().describe('Field values for the new account. An account with the same name is reused.'),
|
|
297
|
+
opportunity: DATA_ARG.optional().describe('Field values for a new opportunity. Omit to create none.'),
|
|
298
|
+
transfer_related_to: z
|
|
299
|
+
.array(z.enum(['contact', 'account', 'potential']))
|
|
300
|
+
.optional()
|
|
301
|
+
.describe("Where the lead's related records go. potential means the opportunity."),
|
|
302
|
+
}),
|
|
303
|
+
annotations: WRITE_REPLACE_ANNOTATIONS,
|
|
304
|
+
}, async (args) => {
|
|
305
|
+
try {
|
|
306
|
+
const { body } = await writeClient.convertLead(args.lead_id, {
|
|
307
|
+
contact: args.contact ?? {},
|
|
308
|
+
account: args.account ?? {},
|
|
309
|
+
...(args.opportunity === undefined ? {} : { potential: args.opportunity }),
|
|
310
|
+
...(args.transfer_related_to === undefined ? {} : { transfer_to: args.transfer_related_to }),
|
|
311
|
+
}, { context: { module: 'leads' } });
|
|
312
|
+
const made = body?.data ?? {};
|
|
313
|
+
const present = (record) => {
|
|
314
|
+
const id = record?.id;
|
|
315
|
+
if (typeof id === 'number')
|
|
316
|
+
return String(id);
|
|
317
|
+
return typeof id === 'string' && id !== '' ? id : undefined;
|
|
318
|
+
};
|
|
319
|
+
const contactId = present(made.contact);
|
|
320
|
+
const accountId = present(made.account);
|
|
321
|
+
const opportunityId = present(made.potential);
|
|
322
|
+
if (contactId === undefined && accountId === undefined && opportunityId === undefined) {
|
|
323
|
+
return {
|
|
324
|
+
content: [
|
|
325
|
+
{
|
|
326
|
+
type: 'text',
|
|
327
|
+
text: `The CRM accepted the conversion of lead ${args.lead_id} but did not return the new records. Check the lead and its contact before you try again; there is no undo.`,
|
|
328
|
+
},
|
|
329
|
+
],
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
const parts = [];
|
|
333
|
+
if (contactId !== undefined)
|
|
334
|
+
parts.push(`contact ${contactId}`);
|
|
335
|
+
if (accountId !== undefined)
|
|
336
|
+
parts.push(`account ${accountId} (reused if the name existed)`);
|
|
337
|
+
if (opportunityId !== undefined)
|
|
338
|
+
parts.push(`opportunity ${opportunityId}`);
|
|
339
|
+
const lines = [
|
|
340
|
+
`Converted lead ${args.lead_id}: ${parts.join(', ')}.`,
|
|
341
|
+
'There is no undo. Converting the same lead again is refused (409), so check the lead before any retry.',
|
|
342
|
+
];
|
|
343
|
+
if (args.opportunity !== undefined && opportunityId === undefined) {
|
|
344
|
+
lines.push("An opportunity was requested but the CRM did not return one; check the account's opportunities.");
|
|
345
|
+
}
|
|
346
|
+
return { content: [{ type: 'text', text: lines.join('\n') }] };
|
|
347
|
+
}
|
|
348
|
+
catch (error) {
|
|
349
|
+
return toToolResult(error);
|
|
350
|
+
}
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
//# sourceMappingURL=writes.js.map
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { McpServer } from '@modelcontextprotocol/server';
|
|
2
|
+
/** Added to every schema rejection so the assistant knows nothing was sent and what to try next. */
|
|
3
|
+
export declare const SCHEMA_NEXT_STEP: string;
|
|
4
|
+
/** A limit message that carries its own next step, for `.max()` checks. */
|
|
5
|
+
export declare function limitMessage(what: string, max: number): string;
|
|
6
|
+
/**
|
|
7
|
+
* Makes every schema rejection say that no request was made and what to do next.
|
|
8
|
+
*
|
|
9
|
+
* The SDK prints all issues of a failed parse, joined, inside "Invalid arguments for tool …".
|
|
10
|
+
* zod gives no hook at the end of a parse, and its issue messages are built from the inside out
|
|
11
|
+
* (a union's own issue is created after the issues of its options), so no per-issue rule can
|
|
12
|
+
* find the one that matters. The suffix is therefore added after the parse, once, to the last
|
|
13
|
+
* issue of the result. Every tool input schema is wrapped when the tool is registered.
|
|
14
|
+
*/
|
|
15
|
+
export declare function addNextStepToRejections(server: McpServer): void;
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
/** Added to every schema rejection so the assistant knows nothing was sent and what to try next. */
|
|
3
|
+
export const SCHEMA_NEXT_STEP = 'No request was made. Next step: correct this argument and call again — ' +
|
|
4
|
+
'initiative_describe_module lists field names, and initiative_help explains the rules.';
|
|
5
|
+
/** Issues printed in full; the SDK adds every issue's path to the text, so the rest are counted. */
|
|
6
|
+
const FULL_ISSUES = 5;
|
|
7
|
+
/** A limit message that carries its own next step, for `.max()` checks. */
|
|
8
|
+
export function limitMessage(what, max) {
|
|
9
|
+
return `${what} takes at most ${max} entries. No request was made. Next step: send fewer entries, or split the work into several calls.`;
|
|
10
|
+
}
|
|
11
|
+
/** Keeps the first issues, counts the rest, and puts the suffix on the last issue the SDK prints. */
|
|
12
|
+
function withNextStep(result) {
|
|
13
|
+
const issues = result.issues;
|
|
14
|
+
if (issues === undefined || issues.length === 0)
|
|
15
|
+
return result;
|
|
16
|
+
const shown = issues.slice(0, FULL_ISSUES).map((issue) => ({ ...issue }));
|
|
17
|
+
const hidden = issues.length - shown.length;
|
|
18
|
+
const last = shown[shown.length - 1];
|
|
19
|
+
const more = hidden > 0 ? ` (and ${hidden} more problems)` : '';
|
|
20
|
+
// A per-schema message (limitMessage, a custom since message) may already say "No request was
|
|
21
|
+
// made". Say it once: keep it on the last issue that has it, and take it off the others.
|
|
22
|
+
const marker = 'No request was made';
|
|
23
|
+
let lastCarrier = -1;
|
|
24
|
+
shown.forEach((issue, index) => {
|
|
25
|
+
if (issue.message.includes(marker))
|
|
26
|
+
lastCarrier = index;
|
|
27
|
+
});
|
|
28
|
+
shown.forEach((issue, index) => {
|
|
29
|
+
if (index !== lastCarrier && issue.message.includes(marker)) {
|
|
30
|
+
issue.message = issue.message.replace(`${marker}. `, '');
|
|
31
|
+
}
|
|
32
|
+
});
|
|
33
|
+
if (lastCarrier === -1) {
|
|
34
|
+
last.message = `${last.message.replace(/\.+$/, '')}${more}. ${SCHEMA_NEXT_STEP}`;
|
|
35
|
+
}
|
|
36
|
+
else if (more !== '') {
|
|
37
|
+
last.message = `${last.message}${more}`;
|
|
38
|
+
}
|
|
39
|
+
return { ...result, issues: shown };
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Makes every schema rejection say that no request was made and what to do next.
|
|
43
|
+
*
|
|
44
|
+
* The SDK prints all issues of a failed parse, joined, inside "Invalid arguments for tool …".
|
|
45
|
+
* zod gives no hook at the end of a parse, and its issue messages are built from the inside out
|
|
46
|
+
* (a union's own issue is created after the issues of its options), so no per-issue rule can
|
|
47
|
+
* find the one that matters. The suffix is therefore added after the parse, once, to the last
|
|
48
|
+
* issue of the result. Every tool input schema is wrapped when the tool is registered.
|
|
49
|
+
*/
|
|
50
|
+
export function addNextStepToRejections(server) {
|
|
51
|
+
const original = server.registerTool.bind(server);
|
|
52
|
+
server.registerTool = (name, config, handler) => {
|
|
53
|
+
let schema = config.inputSchema;
|
|
54
|
+
if (schema === undefined)
|
|
55
|
+
return original(name, config, handler);
|
|
56
|
+
// A plain raw shape ({ topic: z.string() }) has no validator of its own; make it a z.object
|
|
57
|
+
// so no tool can slip past the wrapper.
|
|
58
|
+
if (schema['~standard'] === undefined) {
|
|
59
|
+
schema = z.object(schema);
|
|
60
|
+
}
|
|
61
|
+
const standard = schema?.['~standard'];
|
|
62
|
+
if (standard === undefined)
|
|
63
|
+
throw new Error(`Tool ${name} has an input schema this server cannot guard.`);
|
|
64
|
+
const wrapped = Object.create(schema, {
|
|
65
|
+
'~standard': {
|
|
66
|
+
value: {
|
|
67
|
+
...standard,
|
|
68
|
+
validate: (value) => {
|
|
69
|
+
const out = standard.validate(value);
|
|
70
|
+
return out instanceof Promise
|
|
71
|
+
? out.then((r) => withNextStep(r))
|
|
72
|
+
: withNextStep(out);
|
|
73
|
+
},
|
|
74
|
+
},
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
return original(name, { ...config, inputSchema: wrapped }, handler);
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
//# sourceMappingURL=validation.js.map
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { Config } from './config.js';
|
|
2
|
+
import type { InitiativeWriteClient } from './services/write-client.js';
|
|
3
|
+
/** The write client exists only when a switch is on, so a read-only run never builds anything that can write. */
|
|
4
|
+
export declare function buildWriteClient(config: Config, factory: () => InitiativeWriteClient): InitiativeWriteClient | undefined;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/** The write client exists only when a switch is on, so a read-only run never builds anything that can write. */
|
|
2
|
+
export function buildWriteClient(config, factory) {
|
|
3
|
+
return config.allowWrites || config.allowDeletes ? factory() : undefined;
|
|
4
|
+
}
|
|
5
|
+
//# sourceMappingURL=write-wiring.js.map
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
# Initiative CRM MCP server: install guide (preview)
|
|
2
|
+
|
|
3
|
+
Language: English | [Français](../fr/install.md)
|
|
4
|
+
|
|
5
|
+
## 1. What this is
|
|
6
|
+
|
|
7
|
+
The Initiative CRM MCP server connects an AI assistant to your Initiative CRM. You ask a question in plain language. The assistant reads your accounts, contacts, opportunities, quotes and invoices and answers.
|
|
8
|
+
|
|
9
|
+
MCP means Model Context Protocol. It is a standard way for an assistant to use an outside tool.
|
|
10
|
+
|
|
11
|
+
The server runs on your own computer. It works with Claude Desktop, Claude Code and Cursor. It does not work with web assistants such as ChatGPT or claude.ai.
|
|
12
|
+
|
|
13
|
+
This is a preview. It is an early version for design partners. Some things will change before the general release. Please tell us what you find (see section 9).
|
|
14
|
+
|
|
15
|
+
The assistant acts as you. It has the same permissions as your Initiative user.
|
|
16
|
+
|
|
17
|
+
## 2. Before you start
|
|
18
|
+
|
|
19
|
+
You need two things:
|
|
20
|
+
|
|
21
|
+
- Node 20 or later. Node is the program that runs the server. To check your version, run `node --version` in a terminal.
|
|
22
|
+
- An Initiative user account.
|
|
23
|
+
|
|
24
|
+
The token contains your instance name. You do not need to give the address of the Initiative API, because the server already has it (see section 5).
|
|
25
|
+
|
|
26
|
+
## 3. Create your API token
|
|
27
|
+
|
|
28
|
+
An API token is a secret key. It lets the server act as you in Initiative.
|
|
29
|
+
|
|
30
|
+
1. Open Initiative in your browser.
|
|
31
|
+
2. Go to **My Preferences, then API Tokens**.
|
|
32
|
+
3. Create a token.
|
|
33
|
+
4. Copy the token at once. It looks like `itv_YXBpdG9rZW4_a1b2c3...`.
|
|
34
|
+
|
|
35
|
+
Treat the token like a password:
|
|
36
|
+
|
|
37
|
+
- Do not paste it in a chat, an email or a screenshot.
|
|
38
|
+
- The token is stored as plain text in your assistant configuration file. Anyone who can read that file can act as you.
|
|
39
|
+
- A token cannot be made read-only. It carries all the permissions of your user.
|
|
40
|
+
|
|
41
|
+
## 4. Connect your assistant
|
|
42
|
+
|
|
43
|
+
The connector is published on npm as `@initiativesolutions/crm-mcp-server`. The command `npx` downloads it and starts it. `npx` is installed together with Node.
|
|
44
|
+
|
|
45
|
+
In the examples below, replace `itv_YOUR_TOKEN_HERE` with your API token.
|
|
46
|
+
|
|
47
|
+
The examples name a fixed version: `@0.5.0`. Your assistant keeps this version until you change the number. When Initiative announces a new version, change the number in your configuration and restart your assistant.
|
|
48
|
+
|
|
49
|
+
### Claude Desktop
|
|
50
|
+
|
|
51
|
+
1. Open **Settings, then Developer, then Edit Config**. This opens the file `claude_desktop_config.json`.
|
|
52
|
+
- macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
|
|
53
|
+
- Windows: `%APPDATA%\Claude\claude_desktop_config.json`
|
|
54
|
+
2. Add the `initiative` entry:
|
|
55
|
+
|
|
56
|
+
```json
|
|
57
|
+
{
|
|
58
|
+
"mcpServers": {
|
|
59
|
+
"initiative": {
|
|
60
|
+
"command": "npx",
|
|
61
|
+
"args": ["-y", "@initiativesolutions/crm-mcp-server@0.5.0"],
|
|
62
|
+
"env": {
|
|
63
|
+
"INITIATIVE_API_TOKEN": "itv_YOUR_TOKEN_HERE"
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
3. Save the file and restart Claude Desktop.
|
|
71
|
+
|
|
72
|
+
If Claude Desktop cannot find `npx`, for example when Node was installed with nvm, use the absolute path to `npx` as the `command`. Find it with `which npx` on macOS or Linux, or `where npx` on Windows.
|
|
73
|
+
|
|
74
|
+
### Claude Code
|
|
75
|
+
|
|
76
|
+
Run this command in a terminal. The option `--scope user` makes the server available in all your projects.
|
|
77
|
+
|
|
78
|
+
```bash
|
|
79
|
+
claude mcp add initiative --scope user --env INITIATIVE_API_TOKEN=itv_YOUR_TOKEN_HERE \
|
|
80
|
+
-- npx -y @initiativesolutions/crm-mcp-server@0.5.0
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
### Cursor
|
|
84
|
+
|
|
85
|
+
Add the `initiative` entry to the file `~/.cursor/mcp.json`. To connect one project only, use the file `.cursor/mcp.json` in that project.
|
|
86
|
+
|
|
87
|
+
```json
|
|
88
|
+
{
|
|
89
|
+
"mcpServers": {
|
|
90
|
+
"initiative": {
|
|
91
|
+
"command": "npx",
|
|
92
|
+
"args": ["-y", "@initiativesolutions/crm-mcp-server@0.5.0"],
|
|
93
|
+
"env": {
|
|
94
|
+
"INITIATIVE_API_TOKEN": "itv_YOUR_TOKEN_HERE"
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
### Check that it works
|
|
102
|
+
|
|
103
|
+
Ask your assistant: "Who am I in Initiative?" The answer gives the name of your instance and your user.
|
|
104
|
+
|
|
105
|
+
## 5. Settings
|
|
106
|
+
|
|
107
|
+
You set each setting in the `env` block of the configuration, as the token is set above. Restart the assistant after each change.
|
|
108
|
+
|
|
109
|
+
| Setting | Default | What it does |
|
|
110
|
+
|---|---|---|
|
|
111
|
+
| `INITIATIVE_API_TOKEN` | none (required) | Your API token. The server checks its shape when it starts. |
|
|
112
|
+
| `INITIATIVE_BASE_URL` | `https://app.initiative-crm.com/api/v1` | The address of the Initiative API. Change it only for a test environment. |
|
|
113
|
+
| `INITIATIVE_ALLOW_WRITES` | `false` | Allows the assistant to change data. See section 6. |
|
|
114
|
+
| `INITIATIVE_ALLOW_DELETES` | `false` | Allows the assistant to delete data. See section 6. |
|
|
115
|
+
| `INITIATIVE_UPLOAD_DIR` | not set (off) | The one folder from which the assistant may upload files by path. Use an absolute path. |
|
|
116
|
+
| `INITIATIVE_MAX_RESPONSE_CHARS` | `25000` | The maximum size of one answer, in characters. The minimum is `1000`. |
|
|
117
|
+
|
|
118
|
+
The two switches accept `true` or `false`. They also accept `1` or `0`, `yes` or `no`, and `on` or `off`. Any other value stops the server at start, with a message.
|
|
119
|
+
|
|
120
|
+
## 6. Safety
|
|
121
|
+
|
|
122
|
+
### Read-only by default
|
|
123
|
+
|
|
124
|
+
With the default settings, the assistant can only read. The tools that change data are not offered to it at all. You cannot ask it to use them.
|
|
125
|
+
|
|
126
|
+
### What each switch adds
|
|
127
|
+
|
|
128
|
+
Because the token carries all your permissions, the switches are the only limit on the assistant. Enable only what you need.
|
|
129
|
+
|
|
130
|
+
| Switch | Tools it adds |
|
|
131
|
+
|---|---|
|
|
132
|
+
| `INITIATIVE_ALLOW_WRITES=true` | `initiative_create_record`, `initiative_update_record`, `initiative_link_records`, `initiative_add_comment`, `initiative_upload_document`, `initiative_convert_lead`, `initiative_set_line_items` |
|
|
133
|
+
| `INITIATIVE_ALLOW_DELETES=true` | `initiative_delete_record`, `initiative_unlink_records` |
|
|
134
|
+
|
|
135
|
+
Each switch works alone. Initiative can still refuse an action that your user is not allowed to do.
|
|
136
|
+
|
|
137
|
+
### Deletes are permanent
|
|
138
|
+
|
|
139
|
+
A delete cannot be undone, neither in the API nor in this server. The assistant is told to ask you before it deletes.
|
|
140
|
+
|
|
141
|
+
Converting a lead into a contact and an account has no undo either. Check the lead first.
|
|
142
|
+
|
|
143
|
+
### Lines of a quote, invoice or order
|
|
144
|
+
|
|
145
|
+
When lines are sent to Initiative, they replace the whole list. Nothing is merged. A mistake can destroy the lines of a document.
|
|
146
|
+
|
|
147
|
+
For this reason, the server has one tool for lines, `initiative_set_line_items`. The assistant must follow these steps:
|
|
148
|
+
|
|
149
|
+
1. Read the current lines first. The tool returns a complete list and a `lines_version`.
|
|
150
|
+
2. Change that list.
|
|
151
|
+
3. Send the complete list back, with the `lines_version`.
|
|
152
|
+
|
|
153
|
+
If someone else changed the lines in the meantime, the server refuses the change. The assistant must then read again.
|
|
154
|
+
|
|
155
|
+
A replace keeps only the fields of the list. Every line gets a new id. Tax is calculated again. Extra stored values are lost, for example several discounts on one line.
|
|
156
|
+
|
|
157
|
+
### A write with an unknown result is never repeated
|
|
158
|
+
|
|
159
|
+
Sometimes a request times out or the connection breaks after the request left. The server cannot know if Initiative applied the change. It does not send the request again.
|
|
160
|
+
|
|
161
|
+
The assistant must read the record first, and only then try again.
|
|
162
|
+
|
|
163
|
+
### The upload folder
|
|
164
|
+
|
|
165
|
+
The assistant can send a file in two ways. It can send the content directly, up to 10 MB. This always works with `INITIATIVE_ALLOW_WRITES=true`. Or it can read a file from your disk by its path. This is off, unless you set `INITIATIVE_UPLOAD_DIR`.
|
|
166
|
+
|
|
167
|
+
Text in the CRM can be written by other people. A hidden instruction in that text could try to make the assistant upload a private file, for example an SSH key. The upload folder limits this.
|
|
168
|
+
|
|
169
|
+
- Create a folder only for uploads. Do not use your home folder or your Documents folder.
|
|
170
|
+
- Every file in that folder can be sent to the CRM.
|
|
171
|
+
- The limit applies to this server only. If your assistant has its own file or shell tools, it can read other files with them.
|
|
172
|
+
|
|
173
|
+
## 7. When something goes wrong
|
|
174
|
+
|
|
175
|
+
Every error message says what went wrong and what to do next.
|
|
176
|
+
|
|
177
|
+
When Initiative answered the request, the message also gives a **Request id**. Send this id to support. It helps us find the exact request.
|
|
178
|
+
|
|
179
|
+
If the server does not start, it stops with a message. Some assistants hide this message. Look for it here:
|
|
180
|
+
|
|
181
|
+
- Claude Desktop: **Settings, then Developer**, then open the log for `initiative`.
|
|
182
|
+
- Claude Code: the message appears in the terminal.
|
|
183
|
+
- Cursor: the **Output** panel, channel **MCP**.
|
|
184
|
+
|
|
185
|
+
The most common causes are a missing `INITIATIVE_API_TOKEN`, and a token that is not complete. A token starts with `itv_`, then a code, an underscore, then 64 hexadecimal characters. Paste the whole value, with no spaces.
|
|
186
|
+
|
|
187
|
+
When you contact support, send:
|
|
188
|
+
|
|
189
|
+
- the message of the error,
|
|
190
|
+
- the Request id, if there is one,
|
|
191
|
+
- the version of the server (`0.5.0`),
|
|
192
|
+
- what you asked the assistant.
|
|
193
|
+
|
|
194
|
+
Never send your API token.
|
|
195
|
+
|
|
196
|
+
## 8. Remove the server
|
|
197
|
+
|
|
198
|
+
1. Delete the `initiative` entry from the configuration of your assistant. For Claude Code, run `claude mcp remove initiative`. Restart the assistant.
|
|
199
|
+
2. In Initiative, go to **My Preferences, then API Tokens**. Delete the token. This takes effect at once.
|
|
200
|
+
3. Delete the upload folder if you no longer need it.
|
|
201
|
+
|
|
202
|
+
## 9. Give feedback
|
|
203
|
+
|
|
204
|
+
Your feedback is the reason for this preview. Tell us what worked, what did not, and what is missing.
|
|
205
|
+
|
|
206
|
+
Send feedback to: <contact to be provided by Initiative>
|