@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.
Files changed (79) hide show
  1. package/README.md +192 -2
  2. package/dist/config.d.ts +36 -0
  3. package/dist/config.js +125 -0
  4. package/dist/constants.d.ts +51 -0
  5. package/dist/constants.js +68 -0
  6. package/dist/errors.d.ts +60 -0
  7. package/dist/errors.js +399 -0
  8. package/dist/field-sets.d.ts +37 -0
  9. package/dist/field-sets.js +97 -0
  10. package/dist/fold.d.ts +2 -0
  11. package/dist/fold.js +5 -0
  12. package/dist/guides.d.ts +37 -0
  13. package/dist/guides.js +80 -0
  14. package/dist/index.d.ts +2 -0
  15. package/dist/index.js +28 -0
  16. package/dist/render.d.ts +53 -0
  17. package/dist/render.js +237 -0
  18. package/dist/server.d.ts +25 -0
  19. package/dist/server.js +89 -0
  20. package/dist/services/api-client.d.ts +42 -0
  21. package/dist/services/api-client.js +40 -0
  22. package/dist/services/path.d.ts +9 -0
  23. package/dist/services/path.js +33 -0
  24. package/dist/services/query.d.ts +7 -0
  25. package/dist/services/query.js +56 -0
  26. package/dist/services/transport.d.ts +48 -0
  27. package/dist/services/transport.js +264 -0
  28. package/dist/services/upload-source.d.ts +26 -0
  29. package/dist/services/upload-source.js +206 -0
  30. package/dist/services/write-client.d.ts +34 -0
  31. package/dist/services/write-client.js +57 -0
  32. package/dist/token-source.d.ts +21 -0
  33. package/dist/token-source.js +11 -0
  34. package/dist/tools/deletes.d.ts +3 -0
  35. package/dist/tools/deletes.js +54 -0
  36. package/dist/tools/discovery.d.ts +4 -0
  37. package/dist/tools/discovery.js +165 -0
  38. package/dist/tools/help.d.ts +3 -0
  39. package/dist/tools/help.js +96 -0
  40. package/dist/tools/lines.d.ts +33 -0
  41. package/dist/tools/lines.js +285 -0
  42. package/dist/tools/records.d.ts +14 -0
  43. package/dist/tools/records.js +141 -0
  44. package/dist/tools/relations.d.ts +4 -0
  45. package/dist/tools/relations.js +97 -0
  46. package/dist/tools/schemas.d.ts +76 -0
  47. package/dist/tools/schemas.js +59 -0
  48. package/dist/tools/sync.d.ts +4 -0
  49. package/dist/tools/sync.js +107 -0
  50. package/dist/tools/writes.d.ts +4 -0
  51. package/dist/tools/writes.js +353 -0
  52. package/dist/validation.d.ts +15 -0
  53. package/dist/validation.js +80 -0
  54. package/dist/write-wiring.d.ts +4 -0
  55. package/dist/write-wiring.js +5 -0
  56. package/docs/partners/en/install.md +206 -0
  57. package/docs/partners/fr/install.md +206 -0
  58. package/guides/en/best-practices.md +134 -0
  59. package/guides/en/converting-leads.md +189 -0
  60. package/guides/en/fields-and-formats.md +365 -0
  61. package/guides/en/inventory-documents.md +252 -0
  62. package/guides/en/linking-records.md +266 -0
  63. package/guides/en/price-books.md +233 -0
  64. package/guides/en/querying-records.md +197 -0
  65. package/guides/en/syncing-data.md +276 -0
  66. package/guides/en/uploading-documents.md +194 -0
  67. package/guides/en/writing-records.md +239 -0
  68. package/guides/fr/best-practices.md +134 -0
  69. package/guides/fr/converting-leads.md +189 -0
  70. package/guides/fr/fields-and-formats.md +365 -0
  71. package/guides/fr/inventory-documents.md +252 -0
  72. package/guides/fr/linking-records.md +266 -0
  73. package/guides/fr/price-books.md +233 -0
  74. package/guides/fr/querying-records.md +197 -0
  75. package/guides/fr/syncing-data.md +277 -0
  76. package/guides/fr/uploading-documents.md +194 -0
  77. package/guides/fr/writing-records.md +239 -0
  78. package/guides/manifest.json +174 -0
  79. package/package.json +54 -4
package/dist/index.js ADDED
@@ -0,0 +1,28 @@
1
+ #!/usr/bin/env node
2
+ import { serveStdio } from '@modelcontextprotocol/server/stdio';
3
+ import { ConfigError, loadConfig } from './config.js';
4
+ import { SERVER_NAME } from './constants.js';
5
+ import { createServer } from './server.js';
6
+ import { InitiativeApiClient } from './services/api-client.js';
7
+ import { InitiativeWriteClient } from './services/write-client.js';
8
+ import { StaticTokenSource } from './token-source.js';
9
+ import { buildWriteClient } from './write-wiring.js';
10
+ async function main() {
11
+ const config = loadConfig();
12
+ // One token source for both clients, so they share one rate-limit snapshot.
13
+ const tokenSource = new StaticTokenSource(config.token);
14
+ const client = new InitiativeApiClient(config.baseUrl, tokenSource);
15
+ const writeClient = buildWriteClient(config, () => new InitiativeWriteClient(config.baseUrl, tokenSource));
16
+ await serveStdio(() => createServer({ config, client, ...(writeClient === undefined ? {} : { writeClient }) }));
17
+ }
18
+ main().catch((error) => {
19
+ // stdout carries the JSON-RPC stream. Anything meant for a human goes to stderr, or it corrupts
20
+ // the protocol and the assistant sees a parse error instead of the message.
21
+ if (error instanceof ConfigError) {
22
+ process.stderr.write(`${SERVER_NAME}: ${error.message}\n`);
23
+ process.exit(78); // EX_CONFIG
24
+ }
25
+ process.stderr.write(`${SERVER_NAME}: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}\n`);
26
+ process.exit(1);
27
+ });
28
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Caps a tool answer at the configured character limit.
3
+ *
4
+ * Nothing is ever silently shortened: what is dropped is counted and named, so the assistant knows
5
+ * an answer was cut and can ask for less. Slice 1B grows this file with the record-table renderer
6
+ * and the "N more fields exist" footer that use the same rule.
7
+ */
8
+ export declare function capText(text: string, maxChars: number): string;
9
+ export type ApiRecord = {
10
+ id: string;
11
+ type: string;
12
+ attributes: Record<string, unknown>;
13
+ };
14
+ export type ListMeta = {
15
+ total?: number;
16
+ page?: number;
17
+ per_page?: number;
18
+ pages?: number;
19
+ request_id?: string;
20
+ };
21
+ /**
22
+ * One value as one line of table text. A reference reads "label (#id)", a structure becomes
23
+ * compact JSON. Line breaks and pipes can never break a row, and a long value ends with an
24
+ * ellipsis at `maxChars` (default CELL_MAX_CHARS).
25
+ */
26
+ export declare function formatCell(value: unknown, maxChars?: number): string;
27
+ /** "Records 11–20 of 222 (page 2 of 23)." */
28
+ export declare function pageLine(meta: ListMeta, shown: number): string;
29
+ export declare function renderTable(records: ApiRecord[], columns: string[], meta: ListMeta, opts: {
30
+ maxChars: number;
31
+ module: string;
32
+ moreFields?: number;
33
+ perPageCapped?: boolean;
34
+ /** Default true. The related endpoint returns modifiedtime null, so its caller may leave the column out. */
35
+ includeModifiedtime?: boolean;
36
+ /** 'related' words the footer for a list that has no `fields` argument. Default 'list'. */
37
+ footer?: 'list' | 'related';
38
+ }): string;
39
+ export declare function renderLineItems(items: Record<string, unknown>[]): string;
40
+ export declare function renderTotals(group: unknown): string | undefined;
41
+ /** One record, one `name: value` line per filled field, cut by whole fields at `maxChars`. */
42
+ export declare function renderRecord(record: ApiRecord, opts: {
43
+ maxChars: number;
44
+ labels?: Record<string, string>;
45
+ }): string;
46
+ /**
47
+ * The answer to a create or an update: what happened, the fields the caller sent as the API
48
+ * echoed them, and a count of the other fields that are set. The full record is one
49
+ * initiative_get_record away, so it is not repeated here.
50
+ */
51
+ export declare function renderWriteResult(verb: 'Created' | 'Updated', module: string, record: ApiRecord, sentFields: string[], opts: {
52
+ maxChars: number;
53
+ }): string;
package/dist/render.js ADDED
@@ -0,0 +1,237 @@
1
+ import { CELL_MAX_CHARS } from './constants.js';
2
+ /**
3
+ * Caps a tool answer at the configured character limit.
4
+ *
5
+ * Nothing is ever silently shortened: what is dropped is counted and named, so the assistant knows
6
+ * an answer was cut and can ask for less. Slice 1B grows this file with the record-table renderer
7
+ * and the "N more fields exist" footer that use the same rule.
8
+ */
9
+ export function capText(text, maxChars) {
10
+ if (text.length <= maxChars) {
11
+ return text;
12
+ }
13
+ const notice = (dropped) => `\n\n[Answer truncated: ${dropped} more characters were dropped. Ask a narrower question.]`;
14
+ // Reserve room for the notice itself, sized against the whole input so the digit count can
15
+ // never grow past what was reserved.
16
+ const budget = Math.max(0, maxChars - notice(text.length).length);
17
+ const cut = text.slice(0, budget);
18
+ // Cut on a line boundary so a half-written row never reads as a real one.
19
+ const lastNewline = cut.lastIndexOf('\n');
20
+ const kept = lastNewline > 0 ? cut.slice(0, lastNewline) : cut;
21
+ const result = `${kept}${notice(text.length - kept.length)}`;
22
+ // The notice has a fixed footprint of its own. When maxChars is smaller than that footprint
23
+ // there is no room for both content and notice, so the contract wins: never exceed the cap.
24
+ return result.length <= maxChars ? result : result.slice(0, maxChars);
25
+ }
26
+ const RECORD_VALUE_MAX_CHARS = 1_000;
27
+ function isReference(value) {
28
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
29
+ return false;
30
+ }
31
+ const v = value;
32
+ return 'id' in v && typeof v.label === 'string';
33
+ }
34
+ /**
35
+ * One value as one line of table text. A reference reads "label (#id)", a structure becomes
36
+ * compact JSON. Line breaks and pipes can never break a row, and a long value ends with an
37
+ * ellipsis at `maxChars` (default CELL_MAX_CHARS).
38
+ */
39
+ export function formatCell(value, maxChars = CELL_MAX_CHARS) {
40
+ let text;
41
+ if (value === null || value === undefined) {
42
+ return '';
43
+ }
44
+ else if (typeof value === 'boolean') {
45
+ text = value ? 'yes' : 'no';
46
+ }
47
+ else if (isReference(value)) {
48
+ text = `${value.label} (#${String(value.id)})`;
49
+ }
50
+ else if (typeof value === 'object') {
51
+ text = JSON.stringify(value);
52
+ }
53
+ else {
54
+ text = String(value);
55
+ }
56
+ text = text.replace(/\s+/g, ' ').trim().replace(/\|/g, '\\|');
57
+ return text.length > maxChars ? `${text.slice(0, Math.max(0, maxChars - 1))}…` : text;
58
+ }
59
+ /** "Records 11–20 of 222 (page 2 of 23)." */
60
+ export function pageLine(meta, shown) {
61
+ const page = meta.page ?? 1;
62
+ const perPage = meta.per_page ?? shown;
63
+ const first = (page - 1) * perPage + 1;
64
+ const range = shown === 0 ? '0' : `${first}–${first + shown - 1}`;
65
+ const total = meta.total === undefined ? '' : ` of ${meta.total}`;
66
+ const pages = meta.pages === undefined ? '' : ` (page ${page} of ${meta.pages})`;
67
+ return `Records ${range}${total}${pages}.`;
68
+ }
69
+ function row(cells) {
70
+ return `| ${cells.join(' | ')} |`;
71
+ }
72
+ export function renderTable(records, columns, meta, opts) {
73
+ if (records.length === 0) {
74
+ const page = meta.page ?? 1;
75
+ const text = meta.total === undefined || meta.total === 0
76
+ ? `No ${opts.module} records match.`
77
+ : `0 records on page ${page}. There are ${meta.total} in all, and the last page is ${meta.pages ?? 1}.`;
78
+ return capText(text, opts.maxChars);
79
+ }
80
+ const shownColumns = [
81
+ ...columns.filter((c) => c !== 'id' && c !== 'modifiedtime'),
82
+ ...(opts.includeModifiedtime === false ? [] : ['modifiedtime']),
83
+ ];
84
+ const head = [row(['id', ...shownColumns]), row(['---', ...shownColumns.map(() => '---')])];
85
+ const rows = records.map((r) => row([formatCell(r.id), ...shownColumns.map((c) => formatCell(r.attributes[c]))]));
86
+ const build = (count) => {
87
+ const footer = [pageLine(meta, count)];
88
+ if ((opts.moreFields ?? 0) > 0) {
89
+ footer.push(opts.footer === 'related'
90
+ ? `Showing ${shownColumns.length} fields. Read one record in full with initiative_get_record, ` +
91
+ `or use initiative_list_records on ${opts.module} with fields=[…] for more columns.`
92
+ : `Showing ${shownColumns.length} of ${shownColumns.length + (opts.moreFields ?? 0)} fields. ` +
93
+ 'Ask for more with fields=[…], or read one record with initiative_get_record.');
94
+ }
95
+ if (opts.perPageCapped === true) {
96
+ footer.push('per_page is capped at 100 by the API.');
97
+ }
98
+ const dropped = rows.length - count;
99
+ if (dropped > 0) {
100
+ footer.push(`[Answer shortened: ${dropped} more records on this page were dropped. Ask for fewer fields or a smaller per_page.]`);
101
+ }
102
+ return [...head, ...rows.slice(0, count), '', ...footer].join('\n');
103
+ };
104
+ for (let count = rows.length; count >= 1; count--) {
105
+ const text = build(count);
106
+ if (text.length <= opts.maxChars) {
107
+ return text;
108
+ }
109
+ }
110
+ return capText(build(1), opts.maxChars);
111
+ }
112
+ const LINE_ITEM_COLUMNS = ['product_id', 'service_id', 'quantity', 'unit_price', 'discount', 'line_total'];
113
+ export function renderLineItems(items) {
114
+ const columns = LINE_ITEM_COLUMNS.filter((c) => c !== 'service_id' || items.some((i) => i[c] !== undefined && i[c] !== null));
115
+ return [
116
+ 'line_items:',
117
+ row(columns),
118
+ row(columns.map(() => '---')),
119
+ ...items.map((item) => row(columns.map((c) => formatCell(item[c])))),
120
+ ].join('\n');
121
+ }
122
+ export function renderTotals(group) {
123
+ const totals = group?.totals;
124
+ if (typeof totals !== 'object' || totals === null) {
125
+ return undefined;
126
+ }
127
+ const parts = [`subtotal ${formatCell(totals.subtotal)}`];
128
+ const tax = taxPart(totals);
129
+ if (tax !== undefined) {
130
+ parts.push(tax);
131
+ }
132
+ parts.push(`total ${formatCell(totals.total)}`);
133
+ return `totals: ${parts.join(' · ')}`;
134
+ }
135
+ function asNumber(value) {
136
+ if (typeof value === 'number' && Number.isFinite(value)) {
137
+ return value;
138
+ }
139
+ if (typeof value === 'string' && value.trim() !== '' && Number.isFinite(Number(value))) {
140
+ return Number(value);
141
+ }
142
+ return undefined;
143
+ }
144
+ /**
145
+ * The API puts the tax of a document with tax per line on each line, and sends `tax_total: 0`.
146
+ * Printing "tax 0" there is wrong, because the total includes that tax. So when `tax_total` is 0
147
+ * or absent and the total differs from the subtotal, show the difference with an honest label:
148
+ * it can also hold shipping, an adjustment or a global discount.
149
+ */
150
+ function taxPart(totals) {
151
+ const taxTotal = asNumber(totals.tax_total);
152
+ if (taxTotal !== undefined && taxTotal !== 0) {
153
+ return `tax ${formatCell(totals.tax_total)}`;
154
+ }
155
+ const subtotal = asNumber(totals.subtotal);
156
+ const total = asNumber(totals.total);
157
+ if (subtotal !== undefined && total !== undefined) {
158
+ const difference = Math.round((total - subtotal) * 100) / 100;
159
+ if (difference > 0) {
160
+ return `taxes and other charges ${difference}`;
161
+ }
162
+ if (difference < 0) {
163
+ // A global discount larger than the tax: the amount is a reduction, not a charge.
164
+ return `other changes to the total ${difference}`;
165
+ }
166
+ }
167
+ return taxTotal === 0 ? 'tax 0' : undefined;
168
+ }
169
+ function isEmpty(value) {
170
+ return value === null || value === undefined || value === '' || (Array.isArray(value) && value.length === 0);
171
+ }
172
+ /** One record, one `name: value` line per filled field, cut by whole fields at `maxChars`. */
173
+ export function renderRecord(record, opts) {
174
+ const blocks = [];
175
+ for (const [name, value] of Object.entries(record.attributes)) {
176
+ if (isEmpty(value)) {
177
+ continue;
178
+ }
179
+ if (name === 'line_items' && Array.isArray(value)) {
180
+ blocks.push({ name, text: renderLineItems(value) });
181
+ }
182
+ else if (name === 'group') {
183
+ const totals = renderTotals(value);
184
+ if (totals !== undefined) {
185
+ blocks.push({ name, text: totals });
186
+ }
187
+ }
188
+ else {
189
+ blocks.push({ name, text: `${opts.labels?.[name] ?? name}: ${formatCell(value, RECORD_VALUE_MAX_CHARS)}` });
190
+ }
191
+ }
192
+ const build = (count) => {
193
+ const lines = blocks.slice(0, count).map((b) => b.text);
194
+ if (count < blocks.length) {
195
+ lines.push(`[Answer shortened: fields not shown: ${blocks.slice(count).map((b) => b.name).join(', ')}.]`);
196
+ }
197
+ return lines.join('\n');
198
+ };
199
+ for (let count = blocks.length; count >= 1; count--) {
200
+ const text = build(count);
201
+ if (text.length <= opts.maxChars) {
202
+ return text;
203
+ }
204
+ }
205
+ return capText(build(blocks.length === 0 ? 0 : 1), opts.maxChars);
206
+ }
207
+ /**
208
+ * The answer to a create or an update: what happened, the fields the caller sent as the API
209
+ * echoed them, and a count of the other fields that are set. The full record is one
210
+ * initiative_get_record away, so it is not repeated here.
211
+ */
212
+ export function renderWriteResult(verb, module, record, sentFields, opts) {
213
+ const lines = [`${verb} ${module} ${record.id}.`];
214
+ const missing = [];
215
+ for (const name of sentFields) {
216
+ const value = record.attributes[name];
217
+ if (value !== undefined) {
218
+ lines.push(`${name}: ${formatCell(value, RECORD_VALUE_MAX_CHARS)}`);
219
+ }
220
+ else {
221
+ missing.push(name);
222
+ }
223
+ }
224
+ // The API echoes every field it wrote, so a sent field that is not in the answer was most
225
+ // likely not written, usually because the name is wrong. It goes right after the first line,
226
+ // so a cut answer still carries it.
227
+ if (missing.length > 0) {
228
+ lines.splice(1, 0, `Not in the CRM's answer, probably not written: ${missing.join(', ')}. Check the field names with initiative_describe_module.`);
229
+ }
230
+ const sent = new Set(sentFields);
231
+ const others = Object.entries(record.attributes).filter(([name, value]) => name !== 'id' && !sent.has(name) && !isEmpty(value)).length;
232
+ if (others > 0) {
233
+ lines.push(`${others} other ${others === 1 ? 'field is' : 'fields are'} set; read them with initiative_get_record.`);
234
+ }
235
+ return capText(lines.join('\n'), opts.maxChars);
236
+ }
237
+ //# sourceMappingURL=render.js.map
@@ -0,0 +1,25 @@
1
+ import { McpServer } from '@modelcontextprotocol/server';
2
+ import type { Config } from './config.js';
3
+ import type { InitiativeApiClient } from './services/api-client.js';
4
+ import type { InitiativeWriteClient } from './services/write-client.js';
5
+ export interface ServerDependencies {
6
+ readonly config: Config;
7
+ readonly client: InitiativeApiClient;
8
+ /** Required when `allowWrites` or `allowDeletes` is on; ignored when both are off. */
9
+ readonly writeClient?: InitiativeWriteClient;
10
+ }
11
+ /**
12
+ * What the assistant is told about this connection when it starts.
13
+ *
14
+ * Kept short on purpose: the client puts this in its context for the whole session, so every
15
+ * sentence here is paid for in every message of every conversation.
16
+ */
17
+ export declare function buildInstructions(config: Config): string;
18
+ /**
19
+ * Builds the server and registers the actions this configuration allows.
20
+ *
21
+ * Registration is the enforcement point. An action that is switched off is never registered, so it
22
+ * is absent from tools/list rather than refused at call time — the assistant never learns it
23
+ * exists, and no amount of insistence or prompt manipulation can reach it.
24
+ */
25
+ export declare function createServer({ config, client, writeClient }: ServerDependencies): McpServer;
package/dist/server.js ADDED
@@ -0,0 +1,89 @@
1
+ import { McpServer } from '@modelcontextprotocol/server';
2
+ import { MAX_TOOL_INPUT_ELEMENTS, SERVER_NAME, SERVER_VERSION } from './constants.js';
3
+ import { registerDiscoveryTools } from './tools/discovery.js';
4
+ import { registerHelpTool } from './tools/help.js';
5
+ import { registerLineTools } from './tools/lines.js';
6
+ import { registerRecordTools } from './tools/records.js';
7
+ import { registerRelationTools } from './tools/relations.js';
8
+ import { registerDeleteTools } from './tools/deletes.js';
9
+ import { registerSyncTools } from './tools/sync.js';
10
+ import { registerWriteTools } from './tools/writes.js';
11
+ import { addNextStepToRejections } from './validation.js';
12
+ /**
13
+ * What the assistant is told about this connection when it starts.
14
+ *
15
+ * Kept short on purpose: the client puts this in its context for the whole session, so every
16
+ * sentence here is paid for in every message of every conversation.
17
+ */
18
+ export function buildInstructions(config) {
19
+ const opening = 'Initiative CRM. Every answer comes live from the CRM as the user whose API token this ' +
20
+ "connection carries, with exactly that user's permissions — what they cannot see in the " +
21
+ 'browser, you cannot see here. Nothing is stored between conversations.';
22
+ let posture;
23
+ if (config.allowWrites && config.allowDeletes) {
24
+ posture =
25
+ 'Changing and deleting records are both switched on. Deleting is permanent and has no undo ' +
26
+ 'through this API, so confirm with the user before any delete.';
27
+ }
28
+ else if (config.allowWrites) {
29
+ posture =
30
+ 'Changing records is switched on; deleting is not, so no delete action is offered. To allow ' +
31
+ 'deletions, the person who installed this connector sets INITIATIVE_ALLOW_DELETES=true and ' +
32
+ 'restarts the assistant.';
33
+ }
34
+ else if (config.allowDeletes) {
35
+ posture =
36
+ 'Deleting records is switched on; creating and changing them are not, so no action that ' +
37
+ 'creates or changes anything is offered. Deleting is permanent and has no undo through this ' +
38
+ 'API, so confirm with the user before any delete. To allow changes, the person who installed ' +
39
+ 'this connector sets INITIATIVE_ALLOW_WRITES=true and restarts the assistant.';
40
+ }
41
+ else {
42
+ posture =
43
+ 'This connection is READ-ONLY. No action that creates, changes or deletes anything is ' +
44
+ 'offered, so none can be performed however a request is phrased. If the user wants to ' +
45
+ 'change something, tell them it has to be enabled where the connector is installed: ' +
46
+ 'INITIATIVE_ALLOW_WRITES=true for changes, and INITIATIVE_ALLOW_DELETES=true as well for ' +
47
+ 'deletions, then restart the assistant.';
48
+ }
49
+ const lines = ' Lines of quotes, invoices and orders change only through initiative_set_line_items. Converting a lead ' +
50
+ 'and replacing lines have no undo, so confirm with the user before each one.';
51
+ if (config.allowWrites) {
52
+ posture += lines;
53
+ }
54
+ const guidance = 'Start with initiative_whoami to confirm which CRM instance you are on. Call ' +
55
+ 'initiative_describe_module before writing to a module: field names, mandatory fields and ' +
56
+ 'picklist values differ per customer. Lists are compact: ask for more fields with ' +
57
+ 'fields=[…], read one record in full with initiative_get_record. ' +
58
+ 'When a request is refused, the answer says why and what to do; initiative_help has the full rules.';
59
+ return [opening, posture, guidance].join('\n\n');
60
+ }
61
+ /**
62
+ * Builds the server and registers the actions this configuration allows.
63
+ *
64
+ * Registration is the enforcement point. An action that is switched off is never registered, so it
65
+ * is absent from tools/list rather than refused at call time — the assistant never learns it
66
+ * exists, and no amount of insistence or prompt manipulation can reach it.
67
+ */
68
+ export function createServer({ config, client, writeClient }) {
69
+ if ((config.allowWrites || config.allowDeletes) && writeClient === undefined) {
70
+ throw new Error('A write switch is on but no write client was given. Build one with InitiativeWriteClient.');
71
+ }
72
+ const server = new McpServer({ name: SERVER_NAME, version: SERVER_VERSION }, { instructions: buildInstructions(config), maxToolInputElements: MAX_TOOL_INPUT_ELEMENTS });
73
+ addNextStepToRejections(server);
74
+ registerDiscoveryTools(server, client, config);
75
+ registerRecordTools(server, client, config);
76
+ registerRelationTools(server, client, config);
77
+ registerSyncTools(server, client, config);
78
+ registerHelpTool(server, config);
79
+ // Two separate `if` blocks, never one: deletes have their own switch.
80
+ if (config.allowWrites && writeClient !== undefined) {
81
+ registerWriteTools(server, writeClient, config);
82
+ registerLineTools(server, client, writeClient, config);
83
+ }
84
+ if (config.allowDeletes && writeClient !== undefined) {
85
+ registerDeleteTools(server, writeClient);
86
+ }
87
+ return server;
88
+ }
89
+ //# sourceMappingURL=server.js.map
@@ -0,0 +1,42 @@
1
+ import type { ErrorContext } from '../errors.js';
2
+ import type { TokenSource } from '../token-source.js';
3
+ import { type ApiResponse, type Timing } from './transport.js';
4
+ export type { ApiResponse, RateLimitSnapshot, Timing } from './transport.js';
5
+ /** A record, or a pair list when the same key must appear more than once (filter operators). */
6
+ export type QueryInput = Record<string, string | number> | ReadonlyArray<readonly [string, string | number]>;
7
+ export interface SearchBody {
8
+ filter?: unknown;
9
+ sort?: string;
10
+ order?: 'asc' | 'desc';
11
+ page?: number;
12
+ per_page?: number;
13
+ fields?: string[];
14
+ }
15
+ export interface SearchOptions {
16
+ readonly context?: ErrorContext;
17
+ }
18
+ export interface GetOptions {
19
+ readonly query?: QueryInput;
20
+ /** Extra facts the error mapper needs to give good advice, e.g. the module that was asked for. */
21
+ readonly context?: ErrorContext;
22
+ }
23
+ /**
24
+ * A thin client over Initiative CRM Public API v1.
25
+ *
26
+ * It takes a TokenSource, never a token: on the stdio route that source hands back the same
27
+ * environment token every time, and on the hosted route it will hand back whichever token came in
28
+ * with the request being served. Nothing else in this class changes between the two.
29
+ */
30
+ export declare class InitiativeApiClient {
31
+ private readonly baseUrl;
32
+ private readonly transport;
33
+ constructor(baseUrl: string, tokenSource: TokenSource, fetchImpl?: typeof fetch, timeoutMs?: number, timing?: Timing);
34
+ get<T>(path: string, options?: GetOptions): Promise<ApiResponse<T>>;
35
+ /**
36
+ * The one POST this client makes: the API's read-only search. The module is validated by
37
+ * moduleSegment (a plain slug, nothing else), so it cannot be bent into another path. Every
38
+ * other path is built by the tools from moduleSegment and idSegment, which reject locally. There is deliberately no general write verb.
39
+ */
40
+ search<T>(module: string, body: SearchBody, options?: SearchOptions): Promise<ApiResponse<T>>;
41
+ private buildUrl;
42
+ }
@@ -0,0 +1,40 @@
1
+ import { REQUEST_TIMEOUT_MS } from '../constants.js';
2
+ import { moduleSegment } from './path.js';
3
+ import { REAL_TIMING, Transport } from './transport.js';
4
+ /**
5
+ * A thin client over Initiative CRM Public API v1.
6
+ *
7
+ * It takes a TokenSource, never a token: on the stdio route that source hands back the same
8
+ * environment token every time, and on the hosted route it will hand back whichever token came in
9
+ * with the request being served. Nothing else in this class changes between the two.
10
+ */
11
+ export class InitiativeApiClient {
12
+ baseUrl;
13
+ transport;
14
+ constructor(baseUrl, tokenSource, fetchImpl = globalThis.fetch, timeoutMs = REQUEST_TIMEOUT_MS, timing = REAL_TIMING) {
15
+ this.baseUrl = baseUrl;
16
+ this.transport = new Transport(baseUrl, tokenSource, fetchImpl, timeoutMs, timing);
17
+ }
18
+ async get(path, options = {}) {
19
+ return this.transport.send('GET', this.buildUrl(path, options.query), undefined, options.context);
20
+ }
21
+ /**
22
+ * The one POST this client makes: the API's read-only search. The module is validated by
23
+ * moduleSegment (a plain slug, nothing else), so it cannot be bent into another path. Every
24
+ * other path is built by the tools from moduleSegment and idSegment, which reject locally. There is deliberately no general write verb.
25
+ */
26
+ async search(module, body, options = {}) {
27
+ const url = this.buildUrl(`/${moduleSegment(module)}/search`);
28
+ // A read: slice-1C behaviour, so no write-outcome rule.
29
+ return this.transport.send('POST', url, { json: JSON.stringify(body) }, options.context);
30
+ }
31
+ buildUrl(path, query) {
32
+ const url = new URL(`${this.baseUrl}${path}`);
33
+ const pairs = query === undefined ? [] : Array.isArray(query) ? query : Object.entries(query);
34
+ for (const [key, value] of pairs) {
35
+ url.searchParams.append(key, String(value));
36
+ }
37
+ return url.toString();
38
+ }
39
+ }
40
+ //# sourceMappingURL=api-client.js.map
@@ -0,0 +1,9 @@
1
+ /**
2
+ * A module slug as one URL path segment. Only lower-case letters, digits and hyphens pass, so a
3
+ * slug can never carry a slash, a dot segment, a query or an encoded escape. A well-formed slug
4
+ * that the CRM does not know is not rejected here: the CRM answers 404 and the error mapper lists
5
+ * the valid slugs.
6
+ */
7
+ export declare function moduleSegment(value: string, kind?: 'module' | 'related_module'): string;
8
+ /** A record id as one URL path segment: not empty, not a dot segment, and percent-encoded. */
9
+ export declare function idSegment(value: string): string;
@@ -0,0 +1,33 @@
1
+ import { InitiativeApiError } from '../errors.js';
2
+ const SLUG = /^[a-z][a-z0-9-]*$/;
3
+ function reject(what, shown, valid) {
4
+ return new InitiativeApiError({
5
+ status: null,
6
+ requestSent: false,
7
+ code: 'INVALID_ARGUMENT',
8
+ message: `${what} ${JSON.stringify(shown)} is not valid.`,
9
+ requestId: null,
10
+ retryable: false,
11
+ nextStep: `No request was made. ${valid}`,
12
+ });
13
+ }
14
+ /**
15
+ * A module slug as one URL path segment. Only lower-case letters, digits and hyphens pass, so a
16
+ * slug can never carry a slash, a dot segment, a query or an encoded escape. A well-formed slug
17
+ * that the CRM does not know is not rejected here: the CRM answers 404 and the error mapper lists
18
+ * the valid slugs.
19
+ */
20
+ export function moduleSegment(value, kind = 'module') {
21
+ if (!SLUG.test(value)) {
22
+ throw reject(`The ${kind}`, value, `A ${kind} is a slug such as contacts or purchase-orders: lower-case letters, digits and hyphens, starting with a letter. Use initiative_list_modules to see them.`);
23
+ }
24
+ return value;
25
+ }
26
+ /** A record id as one URL path segment: not empty, not a dot segment, and percent-encoded. */
27
+ export function idSegment(value) {
28
+ if (value === '' || value === '.' || value === '..') {
29
+ throw reject('The id', value, 'A record id is a non-empty string, usually digits such as 49.');
30
+ }
31
+ return encodeURIComponent(value);
32
+ }
33
+ //# sourceMappingURL=path.js.map
@@ -0,0 +1,7 @@
1
+ /** The filter operators the Public API accepts, in the order the guide lists them. */
2
+ export declare const FILTER_OPERATORS: readonly ["eq", "neq", "contains", "starts_with", "gte", "lte", "gt", "lt", "empty", "not_empty", "in"];
3
+ /**
4
+ * Turns the tool's flat filter object into the API's query-string pairs.
5
+ * A key is a field name (equality) or `field[op]`; the value is passed through as given.
6
+ */
7
+ export declare function toFilterPairs(filter: Record<string, string>): Array<[string, string]>;
@@ -0,0 +1,56 @@
1
+ import { InitiativeApiError } from '../errors.js';
2
+ /** The filter operators the Public API accepts, in the order the guide lists them. */
3
+ export const FILTER_OPERATORS = [
4
+ 'eq',
5
+ 'neq',
6
+ 'contains',
7
+ 'starts_with',
8
+ 'gte',
9
+ 'lte',
10
+ 'gt',
11
+ 'lt',
12
+ 'empty',
13
+ 'not_empty',
14
+ 'in',
15
+ ];
16
+ const OPERATOR_KEY = /^([A-Za-z0-9_]+)\[([a-z_]+)\]$/;
17
+ /**
18
+ * Turns the tool's flat filter object into the API's query-string pairs.
19
+ * A key is a field name (equality) or `field[op]`; the value is passed through as given.
20
+ */
21
+ export function toFilterPairs(filter) {
22
+ return Object.entries(filter).map(([key, value]) => {
23
+ const match = OPERATOR_KEY.exec(key);
24
+ if (match === null) {
25
+ if (/[[\]]/.test(key)) {
26
+ throw new InitiativeApiError({
27
+ status: null,
28
+ requestSent: false,
29
+ code: 'INVALID_FILTER',
30
+ message: `Malformed filter key "${key}".`,
31
+ requestId: null,
32
+ retryable: false,
33
+ nextStep: 'No request was made. Write a key as a plain field name, or as field[op] with a ' +
34
+ `lowercase operator from ${FILTER_OPERATORS.join(', ')}. For a search that needs more ` +
35
+ 'than these, use initiative_search_records.',
36
+ });
37
+ }
38
+ return [`filter[${key}]`, value];
39
+ }
40
+ const [, field, operator] = match;
41
+ if (!FILTER_OPERATORS.includes(operator)) {
42
+ throw new InitiativeApiError({
43
+ status: null,
44
+ requestSent: false,
45
+ code: 'INVALID_FILTER',
46
+ message: `Unknown filter operator "${operator}" in "${key}".`,
47
+ requestId: null,
48
+ retryable: false,
49
+ nextStep: `No request was made. Use one of the operators ${FILTER_OPERATORS.join(', ')}, written ` +
50
+ 'as field[op]. For a search that needs more than these, use initiative_search_records.',
51
+ });
52
+ }
53
+ return [`filter[${field}][${operator}]`, value];
54
+ });
55
+ }
56
+ //# sourceMappingURL=query.js.map