@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
package/dist/errors.js
ADDED
|
@@ -0,0 +1,399 @@
|
|
|
1
|
+
import { DETAILS_SHOWN, MODULE_SLUGS } from './constants.js';
|
|
2
|
+
/**
|
|
3
|
+
* A failure the assistant can act on: what happened, whether retrying is worth anything, what to
|
|
4
|
+
* do instead, and the request id support can find in our logs.
|
|
5
|
+
*/
|
|
6
|
+
export class InitiativeApiError extends Error {
|
|
7
|
+
status;
|
|
8
|
+
code;
|
|
9
|
+
requestId;
|
|
10
|
+
retryable;
|
|
11
|
+
nextStep;
|
|
12
|
+
retryAfterSeconds;
|
|
13
|
+
details;
|
|
14
|
+
requestSent;
|
|
15
|
+
constructor(init) {
|
|
16
|
+
super(init.message);
|
|
17
|
+
this.name = 'InitiativeApiError';
|
|
18
|
+
this.status = init.status;
|
|
19
|
+
this.code = init.code;
|
|
20
|
+
this.requestId = init.requestId;
|
|
21
|
+
this.retryable = init.retryable;
|
|
22
|
+
this.nextStep = init.nextStep;
|
|
23
|
+
this.retryAfterSeconds = init.retryAfterSeconds ?? null;
|
|
24
|
+
this.details = init.details ?? [];
|
|
25
|
+
this.requestSent = init.requestSent ?? true;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
/** Every Public API failure uses {"error": {code, message, request_id}}. Some proxies do not. */
|
|
29
|
+
function parseEnvelope(rawBody) {
|
|
30
|
+
let parsed;
|
|
31
|
+
try {
|
|
32
|
+
parsed = JSON.parse(rawBody);
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
if (typeof parsed !== 'object' || parsed === null || !('error' in parsed)) {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
const error = parsed.error;
|
|
41
|
+
if (typeof error !== 'object' || error === null) {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
const record = error;
|
|
45
|
+
return {
|
|
46
|
+
code: typeof record.code === 'string' ? record.code : 'ERROR',
|
|
47
|
+
message: typeof record.message === 'string' ? record.message : 'The API returned an error.',
|
|
48
|
+
requestId: typeof record.request_id === 'string' ? record.request_id : null,
|
|
49
|
+
details: parseDetails(record.details),
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
/** The API lists every field problem of a 422 here. Anything that is not that shape is dropped. */
|
|
53
|
+
function parseDetails(raw) {
|
|
54
|
+
if (!Array.isArray(raw)) {
|
|
55
|
+
return [];
|
|
56
|
+
}
|
|
57
|
+
const details = [];
|
|
58
|
+
for (const item of raw) {
|
|
59
|
+
if (typeof item !== 'object' || item === null) {
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
const entry = item;
|
|
63
|
+
details.push({
|
|
64
|
+
field: typeof entry.field === 'string' ? entry.field : '',
|
|
65
|
+
code: typeof entry.code === 'string' ? entry.code : 'ERROR',
|
|
66
|
+
message: typeof entry.message === 'string' ? entry.message : '',
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
return details;
|
|
70
|
+
}
|
|
71
|
+
function guide(slug) {
|
|
72
|
+
return ` See initiative_help topic "${slug}".`;
|
|
73
|
+
}
|
|
74
|
+
/** The first of these codes (in the table's order) that the response carries, or null. */
|
|
75
|
+
function firstCode(envelope, codes) {
|
|
76
|
+
const present = new Set([envelope.code, ...envelope.details.map((d) => d.code)]);
|
|
77
|
+
return codes.find((code) => present.has(code)) ?? null;
|
|
78
|
+
}
|
|
79
|
+
function validationAdvice(envelope) {
|
|
80
|
+
const code = firstCode(envelope, [
|
|
81
|
+
'REQUIRED',
|
|
82
|
+
'INVALID_OPTION',
|
|
83
|
+
'INVALID_FORMAT',
|
|
84
|
+
'INVALID_TYPE',
|
|
85
|
+
'TOO_LONG',
|
|
86
|
+
'MAX_LENGTH',
|
|
87
|
+
'INVALID_PARENT',
|
|
88
|
+
'REFERENCE_NOT_FOUND',
|
|
89
|
+
'NOT_SUPPORTED',
|
|
90
|
+
'PRICEBOOK_NOT_APPLICABLE',
|
|
91
|
+
'TAX_CONFIGURATION_MISSING',
|
|
92
|
+
'LEAD_CONVERSION_FAILED',
|
|
93
|
+
'INVALID_JSON',
|
|
94
|
+
'INVALID_SHAPE',
|
|
95
|
+
]);
|
|
96
|
+
switch (code) {
|
|
97
|
+
case 'REQUIRED':
|
|
98
|
+
return ('Some mandatory fields have no value. They are named in the problems above. ' +
|
|
99
|
+
'initiative_describe_module shows every mandatory field of a module.' +
|
|
100
|
+
guide('writing-records'));
|
|
101
|
+
case 'INVALID_OPTION':
|
|
102
|
+
return ('A picklist takes the stored value, not the label shown on screen. ' +
|
|
103
|
+
'initiative_describe_module with the field argument lists the values it accepts.' +
|
|
104
|
+
guide('fields-and-formats'));
|
|
105
|
+
case 'INVALID_FORMAT':
|
|
106
|
+
case 'INVALID_TYPE':
|
|
107
|
+
case 'TOO_LONG':
|
|
108
|
+
return ('A value does not fit its field. Correct the value to the field type and length, then ' +
|
|
109
|
+
'send the request again.' +
|
|
110
|
+
guide('fields-and-formats'));
|
|
111
|
+
case 'MAX_LENGTH':
|
|
112
|
+
return ('A value is longer than its field allows. initiative_describe_module shows max_length ' +
|
|
113
|
+
'for each field. Shorten the value, then send the request again.' +
|
|
114
|
+
guide('fields-and-formats'));
|
|
115
|
+
case 'INVALID_PARENT':
|
|
116
|
+
return ('The parent note belongs to another record. Choose a parent note of this same record.' +
|
|
117
|
+
guide('linking-records'));
|
|
118
|
+
case 'REFERENCE_NOT_FOUND':
|
|
119
|
+
return ('The linked record does not exist, or it belongs to the wrong module. ' +
|
|
120
|
+
'Find the right record with initiative_list_records.' +
|
|
121
|
+
guide('linking-records'));
|
|
122
|
+
case 'NOT_SUPPORTED':
|
|
123
|
+
case 'PRICEBOOK_NOT_APPLICABLE':
|
|
124
|
+
case 'TAX_CONFIGURATION_MISSING':
|
|
125
|
+
return ('The API refuses this for a business reason that the message gives. ' +
|
|
126
|
+
'It cannot be done through this connector.' +
|
|
127
|
+
guide('inventory-documents'));
|
|
128
|
+
case 'LEAD_CONVERSION_FAILED':
|
|
129
|
+
return 'The lead conversion failed for the reason in the message.' + guide('converting-leads');
|
|
130
|
+
case 'INVALID_JSON':
|
|
131
|
+
case 'INVALID_SHAPE':
|
|
132
|
+
return ('The connector built a request that the API cannot read. This is a fault in the ' +
|
|
133
|
+
'connector. Report it with the request id below.');
|
|
134
|
+
default:
|
|
135
|
+
return null;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
function parseRetryAfter(headers) {
|
|
139
|
+
const raw = headers.get('Retry-After');
|
|
140
|
+
if (raw === null || !/^\d+$/.test(raw.trim())) {
|
|
141
|
+
return null;
|
|
142
|
+
}
|
|
143
|
+
return Number.parseInt(raw.trim(), 10);
|
|
144
|
+
}
|
|
145
|
+
function nextStepFor(status, envelope, headers, context) {
|
|
146
|
+
if (status === 400 && envelope.code === 'INVALID_FILTER') {
|
|
147
|
+
const message = envelope.message;
|
|
148
|
+
if (message.includes('expected exactly one operator')) {
|
|
149
|
+
return ('A field takes one comparison in initiative_list_records. For a range on one field, or OR ' +
|
|
150
|
+
'across fields, use initiative_search_records.' +
|
|
151
|
+
guide('querying-records'));
|
|
152
|
+
}
|
|
153
|
+
if (/^Unknown (filter |sort )?field/.test(message)) {
|
|
154
|
+
return ('This field name is not in this module. Call initiative_describe_module to get the exact ' +
|
|
155
|
+
'field names. Custom fields start with cf_.' +
|
|
156
|
+
guide('querying-records'));
|
|
157
|
+
}
|
|
158
|
+
if (message.includes('order must be')) {
|
|
159
|
+
return 'The sort order must be asc or desc.';
|
|
160
|
+
}
|
|
161
|
+
if (message.includes("'since' is required")) {
|
|
162
|
+
return ('Deleted records can only be listed from a start date. Give a since value.' +
|
|
163
|
+
guide('syncing-data'));
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
if (status === 401) {
|
|
167
|
+
return ('The API token is invalid, expired or revoked. Retrying will not help. Create a new token ' +
|
|
168
|
+
'in Initiative under My Preferences -> API Tokens and update the connector configuration. ' +
|
|
169
|
+
"An inactive or deleted CRM user's token is refused too.");
|
|
170
|
+
}
|
|
171
|
+
if (status === 409) {
|
|
172
|
+
if (envelope.code === 'INVOICE_NOT_EDITABLE' || envelope.code === 'INVOICE_NOT_DELETABLE') {
|
|
173
|
+
return ('An invoice can change only while it is a draft. This invoice is not a draft, so it ' +
|
|
174
|
+
'cannot be changed through the API.' +
|
|
175
|
+
guide('writing-records'));
|
|
176
|
+
}
|
|
177
|
+
if (envelope.code === 'CONFLICT' && /already converted/i.test(envelope.message)) {
|
|
178
|
+
return ('This lead was converted before, and a conversion cannot be repeated or undone. Do not convert it again. ' +
|
|
179
|
+
'Find the contact it produced with initiative_list_records on contacts.' +
|
|
180
|
+
guide('converting-leads'));
|
|
181
|
+
}
|
|
182
|
+
if (envelope.code === 'CONFLICT') {
|
|
183
|
+
return 'The record changed, or it already exists. Read it again before you decide what to do.';
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
if (status === 422) {
|
|
187
|
+
const advice = validationAdvice(envelope);
|
|
188
|
+
if (advice !== null) {
|
|
189
|
+
return advice;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
if (status === 405) {
|
|
193
|
+
const message = envelope.message;
|
|
194
|
+
if (/is a reference-field reverse/.test(message)) {
|
|
195
|
+
return ('This link is a reference field on the other record. Change the field on that record ' +
|
|
196
|
+
'instead. The message names the field.' +
|
|
197
|
+
guide('linking-records'));
|
|
198
|
+
}
|
|
199
|
+
if (/has no per-relation attributes to update/.test(message)) {
|
|
200
|
+
return ('This link carries no data of its own, so there is nothing to update. Link or unlink ' +
|
|
201
|
+
'the records instead.' +
|
|
202
|
+
guide('linking-records'));
|
|
203
|
+
}
|
|
204
|
+
if (/^Module .+ does not support /.test(message)) {
|
|
205
|
+
return ('This module does not allow this operation. initiative_list_modules shows what each ' +
|
|
206
|
+
'module allows.');
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
if (status === 415) {
|
|
210
|
+
return 'The connector sent the wrong content type. Report it with the request id below.';
|
|
211
|
+
}
|
|
212
|
+
if (status === 403 && envelope.code === 'INSTANCE_SUSPENDED') {
|
|
213
|
+
return ('This Initiative instance is suspended. Nothing can be read or changed until Initiative ' +
|
|
214
|
+
'reactivates it. Retrying will not help.');
|
|
215
|
+
}
|
|
216
|
+
if (status === 403 && envelope.code === 'ADMIN_REQUIRED') {
|
|
217
|
+
return "Only an Initiative administrator's token can do this.";
|
|
218
|
+
}
|
|
219
|
+
if (status === 403) {
|
|
220
|
+
return ('The CRM user this token belongs to is not allowed to do this. It is a permission inside ' +
|
|
221
|
+
'Initiative, not a connector setting — ask an administrator to grant it. The module may also ' +
|
|
222
|
+
'be switched off on this instance; a switched-off module answers 403 even to an administrator.');
|
|
223
|
+
}
|
|
224
|
+
if (status === 404 && context.module !== undefined && envelope.message.startsWith('Unknown module')) {
|
|
225
|
+
return `Unknown module "${context.module}". The modules this API exposes are: ${MODULE_SLUGS.join(', ')}.`;
|
|
226
|
+
}
|
|
227
|
+
if (status === 404 && envelope.message.startsWith('No relation between')) {
|
|
228
|
+
return ('These two modules are not linked. Use initiative_list_related_modules to see which modules ' +
|
|
229
|
+
'this module can be related to.');
|
|
230
|
+
}
|
|
231
|
+
if (status === 404) {
|
|
232
|
+
return ('The record or resource does not exist, or is not visible to this user — the API does not ' +
|
|
233
|
+
'distinguish the two. Check the id, or list the module to find the right one.');
|
|
234
|
+
}
|
|
235
|
+
if (status === 429) {
|
|
236
|
+
const seconds = parseRetryAfter(headers);
|
|
237
|
+
return seconds === null
|
|
238
|
+
? 'The request quota for this token is exhausted. Wait before retrying, and make fewer calls.'
|
|
239
|
+
: `The request quota for this token is exhausted. Wait ${seconds} ${seconds === 1 ? 'second' : 'seconds'} before retrying — ` +
|
|
240
|
+
'retrying sooner will fail again.';
|
|
241
|
+
}
|
|
242
|
+
if (status === 503) {
|
|
243
|
+
return ('The Public API is not enabled on this Initiative instance. That is an instance setting the ' +
|
|
244
|
+
'connector cannot change — ask Initiative to enable it.');
|
|
245
|
+
}
|
|
246
|
+
if (status >= 500) {
|
|
247
|
+
return ('Something failed inside Initiative, not in the request. Do not retry blindly — quote the ' +
|
|
248
|
+
'request id below to Initiative support so they can find the exact request in the logs.');
|
|
249
|
+
}
|
|
250
|
+
return (`The API rejected the request (${envelope.code}). Read the message above, correct the request, ` +
|
|
251
|
+
'and try once more — do not resend it unchanged.');
|
|
252
|
+
}
|
|
253
|
+
/** Turns a non-2xx HTTP response into something an assistant can recover from. */
|
|
254
|
+
export function mapHttpFailure(status, rawBody, headers, context = {}) {
|
|
255
|
+
const envelope = parseEnvelope(rawBody);
|
|
256
|
+
if (envelope === null) {
|
|
257
|
+
return new InitiativeApiError({
|
|
258
|
+
status,
|
|
259
|
+
code: 'INVALID_RESPONSE',
|
|
260
|
+
message: `Initiative answered HTTP ${status} with a body this connector could not read.`,
|
|
261
|
+
requestId: null,
|
|
262
|
+
retryable: false,
|
|
263
|
+
nextStep: 'The response was not the JSON error envelope the API always returns, which usually means ' +
|
|
264
|
+
'something between the connector and Initiative answered instead — a proxy, a gateway or ' +
|
|
265
|
+
'a sign-in page. Check the server address setting.',
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
return new InitiativeApiError({
|
|
269
|
+
status,
|
|
270
|
+
code: envelope.code,
|
|
271
|
+
message: envelope.message,
|
|
272
|
+
requestId: envelope.requestId,
|
|
273
|
+
retryable: status === 429,
|
|
274
|
+
retryAfterSeconds: status === 429 ? parseRetryAfter(headers) : null,
|
|
275
|
+
nextStep: nextStepFor(status, envelope, headers, context),
|
|
276
|
+
details: envelope.details,
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
/** Failures that happen before the request leaves this machine: DNS, a refused connection, TLS. */
|
|
280
|
+
const NOT_SENT_CODES = new Set([
|
|
281
|
+
'ENOTFOUND',
|
|
282
|
+
'EAI_AGAIN',
|
|
283
|
+
'ECONNREFUSED',
|
|
284
|
+
'UNABLE_TO_VERIFY_LEAF_SIGNATURE',
|
|
285
|
+
'DEPTH_ZERO_SELF_SIGNED_CERT',
|
|
286
|
+
'SELF_SIGNED_CERT_IN_CHAIN',
|
|
287
|
+
]);
|
|
288
|
+
function isNotSentCode(code) {
|
|
289
|
+
return NOT_SENT_CODES.has(code) || code.startsWith('ERR_TLS_') || code.startsWith('CERT_');
|
|
290
|
+
}
|
|
291
|
+
/** Node's fetch hides the real error in `cause`, sometimes two levels down. Returns every code found. */
|
|
292
|
+
function causeCodes(error) {
|
|
293
|
+
const codes = [];
|
|
294
|
+
let current = error;
|
|
295
|
+
for (let depth = 0; depth < 5 && typeof current === 'object' && current !== null; depth++) {
|
|
296
|
+
const code = current.code;
|
|
297
|
+
if (typeof code === 'string')
|
|
298
|
+
codes.push(code);
|
|
299
|
+
current = current.cause;
|
|
300
|
+
}
|
|
301
|
+
return codes;
|
|
302
|
+
}
|
|
303
|
+
/** A request that failed in transit: DNS, TLS, a refused or dropped connection, or the timeout. */
|
|
304
|
+
export function networkFailure(cause, url) {
|
|
305
|
+
const detail = cause instanceof Error ? cause.message : String(cause);
|
|
306
|
+
const timedOut = cause instanceof Error && (cause.name === 'TimeoutError' || cause.name === 'AbortError');
|
|
307
|
+
const codes = causeCodes(cause);
|
|
308
|
+
const notSent = !timedOut && codes.length > 0 && codes.some(isNotSentCode);
|
|
309
|
+
const realDetail = (() => {
|
|
310
|
+
let current = cause;
|
|
311
|
+
for (let depth = 0; depth < 5 && current instanceof Error; depth++) {
|
|
312
|
+
const code = current.code;
|
|
313
|
+
if (typeof code === 'string')
|
|
314
|
+
return `${current.message} (${code})`;
|
|
315
|
+
current = current.cause;
|
|
316
|
+
}
|
|
317
|
+
return detail;
|
|
318
|
+
})();
|
|
319
|
+
return new InitiativeApiError({
|
|
320
|
+
status: null,
|
|
321
|
+
// Only a failure before the request left is certain not to have reached Initiative. A reset,
|
|
322
|
+
// a dropped socket, a timeout or an unspecified "fetch failed" may follow a delivered request.
|
|
323
|
+
requestSent: !notSent,
|
|
324
|
+
code: 'NETWORK_ERROR',
|
|
325
|
+
message: timedOut
|
|
326
|
+
? `The request to ${url} took too long and was given up on.`
|
|
327
|
+
: `The request to ${url} could not be completed: ${realDetail}`,
|
|
328
|
+
requestId: null,
|
|
329
|
+
retryable: true,
|
|
330
|
+
nextStep: notSent
|
|
331
|
+
? 'The request never reached Initiative, so nothing was changed. Check that the server ' +
|
|
332
|
+
'address setting is correct and that Initiative is reachable from this machine, then try ' +
|
|
333
|
+
'once more.'
|
|
334
|
+
: 'The request may have reached Initiative, so it may have taken effect. Check the server ' +
|
|
335
|
+
'address setting and that Initiative is reachable from this machine. Before you send a ' +
|
|
336
|
+
'change again, read the record to see whether it was applied.',
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
/** The text an assistant sees. Order matters: what happened, what to do, the request id. */
|
|
340
|
+
export function formatToolFailure(error) {
|
|
341
|
+
const requestId = error.requestSent
|
|
342
|
+
? (error.requestId ?? 'none returned by Initiative')
|
|
343
|
+
: 'none — no request was made.';
|
|
344
|
+
const lines = [
|
|
345
|
+
error.requestSent
|
|
346
|
+
? `Initiative API error (${error.code}): ${error.message}`
|
|
347
|
+
: `Request not sent (${error.code}): ${error.message}`,
|
|
348
|
+
];
|
|
349
|
+
if (error.details.length > 0) {
|
|
350
|
+
lines.push('Problems:');
|
|
351
|
+
for (const d of error.details.slice(0, DETAILS_SHOWN)) {
|
|
352
|
+
const text = d.field === '' ? d.message : d.message === '' ? d.field : `${d.field}: ${d.message}`;
|
|
353
|
+
lines.push(`- ${text === '' ? '' : `${text} `}(${d.code})`);
|
|
354
|
+
}
|
|
355
|
+
if (error.details.length > DETAILS_SHOWN) {
|
|
356
|
+
lines.push(`- … and ${error.details.length - DETAILS_SHOWN} more.`);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
lines.push(`Next step: ${error.nextStep}`, `Request id: ${requestId}`);
|
|
360
|
+
return lines.join('\n');
|
|
361
|
+
}
|
|
362
|
+
/**
|
|
363
|
+
* Wraps any failure as an MCP tool result. Every tool handler ends here on its error path,
|
|
364
|
+
* including for exceptions that are not InitiativeApiError — a bug in this connector must still
|
|
365
|
+
* reach the assistant as a readable answer rather than as a protocol-level error.
|
|
366
|
+
*/
|
|
367
|
+
export function toToolResult(error) {
|
|
368
|
+
const apiError = error instanceof InitiativeApiError
|
|
369
|
+
? error
|
|
370
|
+
: new InitiativeApiError({
|
|
371
|
+
status: null,
|
|
372
|
+
code: 'CONNECTOR_ERROR',
|
|
373
|
+
message: error instanceof Error ? error.message : String(error),
|
|
374
|
+
requestId: null,
|
|
375
|
+
retryable: false,
|
|
376
|
+
nextStep: 'This is a fault in the Initiative connector itself, not in the CRM or the request. ' +
|
|
377
|
+
'Report it with the message above; retrying the same call will fail the same way.',
|
|
378
|
+
});
|
|
379
|
+
return { isError: true, content: [{ type: 'text', text: formatToolFailure(apiError) }] };
|
|
380
|
+
}
|
|
381
|
+
/**
|
|
382
|
+
* initiative_set_line_items refuses a replace when the lines changed after the caller read them.
|
|
383
|
+
* The connector read the document to compare (that GET was sent, so requestSent is true and the
|
|
384
|
+
* request id is the read's), but it did not send the write.
|
|
385
|
+
*/
|
|
386
|
+
export function linesChanged(module, id, sent, current, requestId) {
|
|
387
|
+
return new InitiativeApiError({
|
|
388
|
+
status: null,
|
|
389
|
+
requestSent: true,
|
|
390
|
+
code: 'LINES_CHANGED',
|
|
391
|
+
message: `The lines of ${module} ${id} are not the ones you read: lines_version is now ${current}, and you sent ${sent}. ` +
|
|
392
|
+
'The lines were not changed. The connector only read the document; it did not send the write.',
|
|
393
|
+
requestId,
|
|
394
|
+
retryable: false,
|
|
395
|
+
nextStep: 'Call initiative_set_line_items again without lines to see the current lines and get the new lines_version. ' +
|
|
396
|
+
'Build the complete list from what it shows, then send it with that lines_version.',
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
//# sourceMappingURL=errors.js.map
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { ModuleSlug } from './constants.js';
|
|
2
|
+
import type { ApiResponse, InitiativeApiClient } from './services/api-client.js';
|
|
3
|
+
/**
|
|
4
|
+
* The columns a list answer carries when the assistant did not ask for specific fields: the ones
|
|
5
|
+
* a person scans a list for (what, who, status, when, link). `modifiedtime` is never listed
|
|
6
|
+
* because the API always returns it. Custom fields (cf_*) are never listed: they differ per
|
|
7
|
+
* customer, and a missing one would fail the whole list. The test in tests/field-sets.test.ts
|
|
8
|
+
* checks every name against the describe fixture.
|
|
9
|
+
*/
|
|
10
|
+
export declare const SUMMARY_FIELDS: Readonly<Record<ModuleSlug, readonly string[]>>;
|
|
11
|
+
export interface DescribeField {
|
|
12
|
+
name: string;
|
|
13
|
+
type: string;
|
|
14
|
+
mandatory?: boolean;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* A safe column choice taken from the module's own describe, for when a curated name does not
|
|
18
|
+
* exist on this instance: the mandatory fields (not the owner field, by type), the first text
|
|
19
|
+
* field, and the assigned user.
|
|
20
|
+
*/
|
|
21
|
+
export declare function genericFields(describeFields: DescribeField[]): string[];
|
|
22
|
+
export declare function resolveListFields(module: ModuleSlug | string, requested: string[] | undefined): {
|
|
23
|
+
fields: string[];
|
|
24
|
+
source: 'requested' | 'summary';
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Runs a list with the right columns. It asks for the module's describe at the same time, for the
|
|
28
|
+
* field count the answer must state. If a curated column does not exist on this customer's
|
|
29
|
+
* instance, it keeps the ones that do (or a generic choice) and retries once. Columns the
|
|
30
|
+
* assistant asked for are never changed: that error goes back to the assistant.
|
|
31
|
+
*/
|
|
32
|
+
export declare function listWithFields<T>(module: string, requested: string[] | undefined, run: (fields: string[]) => Promise<ApiResponse<T>>, client: InitiativeApiClient): Promise<{
|
|
33
|
+
response: ApiResponse<T>;
|
|
34
|
+
fields: string[];
|
|
35
|
+
dropped: string[];
|
|
36
|
+
totalFields: number | null;
|
|
37
|
+
}>;
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { moduleSegment } from './services/path.js';
|
|
2
|
+
import { InitiativeApiError } from './errors.js';
|
|
3
|
+
/**
|
|
4
|
+
* The columns a list answer carries when the assistant did not ask for specific fields: the ones
|
|
5
|
+
* a person scans a list for (what, who, status, when, link). `modifiedtime` is never listed
|
|
6
|
+
* because the API always returns it. Custom fields (cf_*) are never listed: they differ per
|
|
7
|
+
* customer, and a missing one would fail the whole list. The test in tests/field-sets.test.ts
|
|
8
|
+
* checks every name against the describe fixture.
|
|
9
|
+
*/
|
|
10
|
+
export const SUMMARY_FIELDS = {
|
|
11
|
+
leads: ['firstname', 'lastname', 'company', 'email', 'phone', 'assigned_user_id'],
|
|
12
|
+
contacts: ['firstname', 'lastname', 'email', 'phone', 'account_id'],
|
|
13
|
+
accounts: ['accountname', 'phone', 'website', 'bill_city', 'assigned_user_id'],
|
|
14
|
+
potentials: ['potentialname', 'related_to', 'sales_stage', 'amount', 'closingdate', 'assigned_user_id'],
|
|
15
|
+
quotes: ['quote_no', 'subject', 'account_id', 'quotestage', 'validtill', 'assigned_user_id'],
|
|
16
|
+
invoices: ['invoice_no', 'subject', 'account_id', 'invoicestatus', 'invoicedate', 'duedate'],
|
|
17
|
+
'purchase-orders': ['purchaseorder_no', 'subject', 'vendor_id', 'duedate', 'assigned_user_id'],
|
|
18
|
+
'sales-orders': ['salesorder_no', 'subject', 'account_id', 'sostatus', 'duedate'],
|
|
19
|
+
products: ['productname', 'productcode', 'productcategory', 'unit_price'],
|
|
20
|
+
services: ['servicename', 'service_no', 'unit_price'],
|
|
21
|
+
pricebooks: ['bookname', 'active'],
|
|
22
|
+
documents: ['notes_title', 'filename', 'folderid', 'assigned_user_id'],
|
|
23
|
+
helpdesk: ['ticket_no', 'ticket_title', 'ticketstatus', 'ticketpriorities', 'parent_id'],
|
|
24
|
+
events: ['subject', 'start_at', 'end_at', 'activitytype', 'parent_id', 'assigned_user_id'],
|
|
25
|
+
tasks: ['subject', 'start_at', 'due_date', 'taskstatus', 'parent_id', 'assigned_user_id'],
|
|
26
|
+
comments: ['commentcontent', 'related_to', 'assigned_user_id'],
|
|
27
|
+
};
|
|
28
|
+
const GENERIC_LIMIT = 6;
|
|
29
|
+
/**
|
|
30
|
+
* A safe column choice taken from the module's own describe, for when a curated name does not
|
|
31
|
+
* exist on this instance: the mandatory fields (not the owner field, by type), the first text
|
|
32
|
+
* field, and the assigned user.
|
|
33
|
+
*/
|
|
34
|
+
export function genericFields(describeFields) {
|
|
35
|
+
const chosen = [];
|
|
36
|
+
const add = (name) => {
|
|
37
|
+
if (name !== undefined && !chosen.includes(name)) {
|
|
38
|
+
chosen.push(name);
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
for (const field of describeFields) {
|
|
42
|
+
if (field.mandatory === true && field.type !== 'owner') {
|
|
43
|
+
add(field.name);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
add(describeFields.find((field) => field.type === 'string')?.name);
|
|
47
|
+
add(describeFields.find((field) => field.name === 'assigned_user_id')?.name);
|
|
48
|
+
return chosen.slice(0, GENERIC_LIMIT);
|
|
49
|
+
}
|
|
50
|
+
export function resolveListFields(module, requested) {
|
|
51
|
+
if (requested !== undefined && requested.length > 0) {
|
|
52
|
+
return { fields: requested, source: 'requested' };
|
|
53
|
+
}
|
|
54
|
+
const curated = SUMMARY_FIELDS[module];
|
|
55
|
+
return { fields: curated === undefined ? [] : [...curated], source: 'summary' };
|
|
56
|
+
}
|
|
57
|
+
function fieldsOf(describe) {
|
|
58
|
+
const fields = describe?.body?.data?.attributes?.fields;
|
|
59
|
+
return Array.isArray(fields) ? fields : null;
|
|
60
|
+
}
|
|
61
|
+
function isUnknownField(error) {
|
|
62
|
+
return (error instanceof InitiativeApiError &&
|
|
63
|
+
error.status === 400 &&
|
|
64
|
+
error.code === 'INVALID_FILTER' &&
|
|
65
|
+
error.message.startsWith('Unknown field'));
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Runs a list with the right columns. It asks for the module's describe at the same time, for the
|
|
69
|
+
* field count the answer must state. If a curated column does not exist on this customer's
|
|
70
|
+
* instance, it keeps the ones that do (or a generic choice) and retries once. Columns the
|
|
71
|
+
* assistant asked for are never changed: that error goes back to the assistant.
|
|
72
|
+
*/
|
|
73
|
+
export async function listWithFields(module, requested, run, client) {
|
|
74
|
+
const { fields, source } = resolveListFields(module, requested);
|
|
75
|
+
const describePromise = client
|
|
76
|
+
.get(`/modules/${moduleSegment(module)}`, { context: { module } })
|
|
77
|
+
.catch(() => null);
|
|
78
|
+
const [listOutcome, describe] = await Promise.all([
|
|
79
|
+
run(fields).then((response) => ({ response }), (error) => ({ error })),
|
|
80
|
+
describePromise,
|
|
81
|
+
]);
|
|
82
|
+
const describeFields = fieldsOf(describe);
|
|
83
|
+
const totalFields = describeFields === null ? null : describeFields.length;
|
|
84
|
+
if ('response' in listOutcome) {
|
|
85
|
+
return { response: listOutcome.response, fields, dropped: [], totalFields };
|
|
86
|
+
}
|
|
87
|
+
if (source === 'requested' || describeFields === null || !isUnknownField(listOutcome.error)) {
|
|
88
|
+
throw listOutcome.error;
|
|
89
|
+
}
|
|
90
|
+
const known = new Set(describeFields.map((field) => field.name));
|
|
91
|
+
const kept = fields.filter((name) => known.has(name));
|
|
92
|
+
const retryFields = kept.length > 0 ? kept : genericFields(describeFields);
|
|
93
|
+
const dropped = fields.filter((name) => !retryFields.includes(name));
|
|
94
|
+
const response = await run(retryFields);
|
|
95
|
+
return { response, fields: retryFields, dropped, totalFields };
|
|
96
|
+
}
|
|
97
|
+
//# sourceMappingURL=field-sets.js.map
|
package/dist/fold.d.ts
ADDED
package/dist/fold.js
ADDED
package/dist/guides.d.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
export type GuideLanguage = 'en' | 'fr';
|
|
2
|
+
export interface GuideEntry {
|
|
3
|
+
readonly slug: string;
|
|
4
|
+
readonly title: string;
|
|
5
|
+
readonly excerpt: string;
|
|
6
|
+
readonly order: number;
|
|
7
|
+
readonly file: string;
|
|
8
|
+
readonly bytes: number;
|
|
9
|
+
}
|
|
10
|
+
export interface GuideManifest {
|
|
11
|
+
readonly source: {
|
|
12
|
+
repository: string;
|
|
13
|
+
ref: string;
|
|
14
|
+
commit: string;
|
|
15
|
+
date: string;
|
|
16
|
+
};
|
|
17
|
+
readonly languages: Record<GuideLanguage, GuideEntry[]>;
|
|
18
|
+
}
|
|
19
|
+
export interface GuideSection {
|
|
20
|
+
readonly heading: string;
|
|
21
|
+
/** The section as written, starting with its `## ` heading line. */
|
|
22
|
+
readonly text: string;
|
|
23
|
+
}
|
|
24
|
+
export interface Guide {
|
|
25
|
+
readonly title: string;
|
|
26
|
+
/** The file without its front matter. */
|
|
27
|
+
readonly body: string;
|
|
28
|
+
readonly sections: GuideSection[];
|
|
29
|
+
/** Text between the front matter and the first `## ` heading. */
|
|
30
|
+
readonly preamble: string;
|
|
31
|
+
}
|
|
32
|
+
/** Reads the manifest on every call; the files are small and never cached. */
|
|
33
|
+
export declare function loadManifest(): GuideManifest;
|
|
34
|
+
/** Loads one guide, or null when the language or slug is not in the manifest. */
|
|
35
|
+
export declare function loadGuide(language: GuideLanguage, slug: string): Guide | null;
|
|
36
|
+
/** Case- and accent-insensitive substring match on the heading, ignoring a `1.` prefix. */
|
|
37
|
+
export declare function findSection(sections: readonly GuideSection[], query: string): GuideSection | null;
|
package/dist/guides.js
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { fold } from './fold.js';
|
|
3
|
+
// Relative to this module: src/ under vitest and dist/ in the package both sit next to guides/.
|
|
4
|
+
const GUIDES_DIR = new URL('../guides/', import.meta.url);
|
|
5
|
+
/** Reads the manifest on every call; the files are small and never cached. */
|
|
6
|
+
export function loadManifest() {
|
|
7
|
+
return JSON.parse(readFileSync(new URL('manifest.json', GUIDES_DIR), 'utf8'));
|
|
8
|
+
}
|
|
9
|
+
function unquote(value) {
|
|
10
|
+
const v = value.trim();
|
|
11
|
+
const quote = v[0];
|
|
12
|
+
if (v.length >= 2 && (quote === '"' || quote === "'") && v.endsWith(quote)) {
|
|
13
|
+
return v.slice(1, -1);
|
|
14
|
+
}
|
|
15
|
+
return v;
|
|
16
|
+
}
|
|
17
|
+
function splitFrontMatter(raw) {
|
|
18
|
+
const text = raw.replace(/^/, '').replace(/\r\n/g, '\n');
|
|
19
|
+
const match = /^---\n([\s\S]*?)\n---\n?/.exec(text);
|
|
20
|
+
if (match === null) {
|
|
21
|
+
return { meta: {}, body: text };
|
|
22
|
+
}
|
|
23
|
+
const meta = {};
|
|
24
|
+
for (const line of (match[1] ?? '').split('\n')) {
|
|
25
|
+
// Split on the first colon only: a title may contain one ("Querying: filtering ...").
|
|
26
|
+
const at = line.indexOf(':');
|
|
27
|
+
if (at > 0) {
|
|
28
|
+
meta[line.slice(0, at).trim()] = unquote(line.slice(at + 1));
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return { meta, body: text.slice(match[0].length) };
|
|
32
|
+
}
|
|
33
|
+
function splitSections(body) {
|
|
34
|
+
const preamble = [];
|
|
35
|
+
const blocks = [];
|
|
36
|
+
let fence = false;
|
|
37
|
+
for (const line of body.split('\n')) {
|
|
38
|
+
if (/^\s*(```|~~~)/.test(line)) {
|
|
39
|
+
fence = !fence;
|
|
40
|
+
}
|
|
41
|
+
if (!fence && line.startsWith('## ')) {
|
|
42
|
+
blocks.push([line]);
|
|
43
|
+
}
|
|
44
|
+
else {
|
|
45
|
+
(blocks.length === 0 ? preamble : blocks[blocks.length - 1]).push(line);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return {
|
|
49
|
+
preamble: preamble.join('\n').trim(),
|
|
50
|
+
sections: blocks.map((lines) => ({
|
|
51
|
+
heading: lines[0].slice(3).trim(),
|
|
52
|
+
text: lines.join('\n').trim(),
|
|
53
|
+
})),
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
/** Loads one guide, or null when the language or slug is not in the manifest. */
|
|
57
|
+
export function loadGuide(language, slug) {
|
|
58
|
+
const entry = loadManifest().languages[language]?.find((e) => e.slug === slug);
|
|
59
|
+
if (entry === undefined) {
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
const { meta, body } = splitFrontMatter(readFileSync(new URL(entry.file, GUIDES_DIR), 'utf8'));
|
|
63
|
+
const { preamble, sections } = splitSections(body);
|
|
64
|
+
return { title: meta.title ?? entry.title, body: body.trim(), sections, preamble };
|
|
65
|
+
}
|
|
66
|
+
/** Case- and accent-insensitive substring match on the heading, ignoring a `1.` prefix. */
|
|
67
|
+
export function findSection(sections, query) {
|
|
68
|
+
const number = /^\s*(\d+)\s*[.)]?\s*$/.exec(query);
|
|
69
|
+
if (number !== null) {
|
|
70
|
+
const byNumber = sections.find((s) => new RegExp(`^\\s*${number[1]}\\s*[.)]`).test(fold(s.heading)));
|
|
71
|
+
if (byNumber !== undefined)
|
|
72
|
+
return byNumber;
|
|
73
|
+
}
|
|
74
|
+
const needle = fold(query).replace(/^\s*\d+\s*[.)]\s*/, '').trim();
|
|
75
|
+
if (needle === '') {
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
return sections.find((s) => fold(s.heading).replace(/^\d+\s*[.)]\s*/, '').includes(needle)) ?? null;
|
|
79
|
+
}
|
|
80
|
+
//# sourceMappingURL=guides.js.map
|
package/dist/index.d.ts
ADDED