conduyt-mcp 4.105.43 → 4.108.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.js CHANGED
@@ -35,8 +35,9 @@ const AMBIGUOUS = " The server may have applied it: read the current state befor
35
35
  /** Room for the nested objects of an error body (a 409 contact_changed's `contact`, a stage-requirements list). */
36
36
  const ERROR_DETAILS_BOUND = 1000;
37
37
  /** Error-body keys that are the actionable state itself and are always rendered WHOLE: HealthFixRefusal.row (the deal's
38
- * current health row, which a caller needs to choose again). The response size cap bounds it. */
39
- const ALWAYS_WHOLE_KEYS = new Set(["row", "metadataConflict"]);
38
+ * current health row, which a caller needs to choose again), and the document reader's 409 creditor_row_exists `existingRow` (the
39
+ * creditor-table row the document matches, which the caller shows instead of filling). The response size cap bounds it. */
40
+ const ALWAYS_WHOLE_KEYS = new Set(["row", "metadataConflict", "existingRow"]);
40
41
  /** Bounded scheme for a refusal's error LISTS (the automation write refusals: AutomationActionConfigKeyError.errors, the 422
41
42
  * AutomationPreflightRefusal.data { message, errors[], warnings[] }) when they do not fit ERROR_DETAILS_BOUND: keep the first
42
43
  * MAX_LISTED_ERRORS entries (warnings: MAX_LISTED_WARNINGS) with every string field capped at MAX_FIELD_CHARS, and close the list with
@@ -65,6 +65,7 @@ import { registerZoomTools } from "./tools/zoom.js";
65
65
  import { registerBookingPageTools } from "./tools/booking-pages.js";
66
66
  import { registerReportTools } from "./tools/reports.js";
67
67
  import { registerReportDashboardTools } from "./tools/dashboards.js";
68
+ import { registerDocumentReaderTools } from "./tools/document-reader.js";
68
69
  /** Registers every Conduyt tool on the server; each tool gets its title + MCP annotations from src/tool-annotations.ts. */
69
70
  export function registerAllTools(server, client) {
70
71
  annotateRegistrations(server);
@@ -135,4 +136,5 @@ export function registerAllTools(server, client) {
135
136
  registerBookingPageTools(server, client);
136
137
  registerReportTools(server, client);
137
138
  registerReportDashboardTools(server, client);
139
+ registerDocumentReaderTools(server, client);
138
140
  }
@@ -470,6 +470,17 @@ export const TOOL_ANNOTATIONS = {
470
470
  conduyt_update_dashboard_tile: update("Update Dashboard Tile"),
471
471
  conduyt_remove_dashboard_tile: destroy("Remove Dashboard Tile"),
472
472
  conduyt_run_dashboard: ro("Run Dashboard"),
473
+ // (ocr65-parity) the document reader (OCR)
474
+ conduyt_list_contact_document_reads: ro("List Contact Document Reads"),
475
+ conduyt_get_document_read: ro("Get Document Read"),
476
+ conduyt_start_document_read: row("Start Document Read", false, true, false), // a restart discards the file's earlier reading and its Filled mark (lib/document-reader/server.ts queueDocumentRead: extracted and filled_* set NULL); each call is a new attempt
477
+ conduyt_fill_deal_from_document_read: row("Fill Deal From Document Read", false, true, false), // writes the deal's custom fields (replacing their values) and one creditor row; a repeat can add another row or answer 409 creditor_row_exists
478
+ conduyt_get_document_reader_types: ro("Get Document Reader Types"),
479
+ conduyt_put_document_reader_types: row("Replace Document Reader Types", false, true, false), // PUT replaces the whole list (types not sent are deleted); every save appends document_reader.types_updated
480
+ conduyt_update_document_reader_enabled: create("Update Document Reader Switch"), // PATCH /settings: every save appends account_settings_changed even when unchanged (as conduyt_update_document_upload_bell); off removes no data
481
+ conduyt_get_document_reader_settings: ro("Get Document Reader Settings"), // (parity66a) GET /settings, the documentReader block only
482
+ conduyt_update_document_reader_settings: create("Update Document Reader Settings"), // (parity66a) PATCH /settings as the switch: every save appends account_settings_changed; autoRead off, a lower dailyLimit or a withdrawn cloud consent deletes nothing and can be set back (readings already stored are kept)
483
+ conduyt_confirm_document_read_values: create("Confirm Document Read Values"), // (parity66a) records { by, at, valueHash } per field and audits document_read.confirmed / unconfirmed on every call; confirmed false takes a confirmation back (re-confirmable), nothing is written to a deal
473
484
  };
474
485
  /**
475
486
  * Wraps server.tool so each tool registered afterwards gets its title and annotations from TOOL_ANNOTATIONS. The registered
@@ -195,7 +195,7 @@ export function registerBulkTools(server, client) {
195
195
  const result = await client.post("/api/v1/bulk/deals/update", params);
196
196
  return formatResult(result);
197
197
  });
198
- server.tool("conduyt_import_preflight", "Pre-check a contact import BEFORE running it — returns criticalWarnings (phone-less list bound for SMS, heavy create-only duplicate skips, double-mapped columns), duplicate/existing-match estimates, invalid emails, DNC/litigator hits, SMS-provider readiness, and plan-limit impact. Same engine the import wizard uses; call this before conduyt_ai_import_contacts on any sizeable list. A workspace whose identifier index is still being built answers 503 `IDENTITY_INDEX_NOT_READY` (nothing checked; retry later). For objectType opportunities (deal files; absent for contacts and companies) the answer also carries dealPipelines (app dealverify64): the pipelines the deal import itself matches rows against, every pipeline of the account including archived ones (an archived pipeline keeps its [Archived] name prefix; a row naming that stored name is matched and refused with the row code pipeline_archived, because no deal can be added to an archived pipeline), each as { id, name, archived, stages: [{ name, isSystem }] } with its live stages in order. Judge a row's Pipeline and Stage cells against this list, as the import does.", {
198
+ server.tool("conduyt_import_preflight", "Pre-check a contact import BEFORE running it — returns criticalWarnings (phone-less list bound for SMS, heavy create-only duplicate skips, double-mapped columns), duplicate/existing-match estimates, invalid emails, DNC/litigator hits, SMS-provider readiness, and plan-limit impact. Same engine the import wizard uses; call this before conduyt_ai_import_contacts on any sizeable list. A workspace whose identifier index is still being built answers 503 `IDENTITY_INDEX_NOT_READY` (nothing checked; retry later). For objectType opportunities (deal files; absent for contacts and companies) the answer also carries dealPipelines (app dealverify64): the pipelines the deal import itself matches rows against, every pipeline of the account including archived ones (an archived pipeline keeps its [Archived] name prefix and, in archivedFromName (app eyeson111), the name it had before (null when not recorded, and on an active pipeline); a row naming either is matched and refused with the row code pipeline_archived, because no deal can be added to an archived pipeline; an active pipeline of the same name always wins), each as { id, name, archived, archivedFromName, stages: [{ name, isSystem }] } with its live stages in order. Judge a row's Pipeline and Stage cells against this list, as the import does.", {
199
199
  objectType: z.enum(["contacts", "opportunities", "companies"]).default("contacts").describe("What the import creates"),
200
200
  importMode: z.enum(["create_and_update", "create_only", "update_only"]).optional().describe("Duplicate handling mode the import will use"),
201
201
  totalRows: z.number().describe("Total rows in the file/payload"),
@@ -20,6 +20,9 @@ export declare const LOSER_ORDER_NOTE = "losers are merged in the order given: f
20
20
  export declare const MERGE_PREVIEW_MAX = 50;
21
21
  export declare const MERGE_PREVIEW_TTL_MS: number;
22
22
  export declare const EMAIL_LOOKUP_NOTE = "Exact email lookup: one address, or up to 20 distinct addresses in an array. Each is trimmed and lower-cased and matches the contact's primary email OR any secondary email slot (email_2 and up); it is an exact match, not a substring search (use `search` for partial text). Combines with every other filter (AND) inside your account and visibility. An empty or invalid address, or more than 20 distinct addresses, is a 400. On a workspace whose identifier index is still being built, the lookup answers 422 when the stored spellings of the requested addresses exceed its stored-spelling bind budget (a count of spellings, not of contacts; other filters do not help); ask support to complete the identifier backfill. Send addresses once; duplicates collapse.";
23
+ /** (parity65pub, app apigaps65b-r4 8d674129ad) what a tag change answers when its COMMIT outcome is unknown; shared by every tool that changes a contact's tags */
24
+ export declare const TAG_OUTCOME_UNKNOWN_NOTE = "A tag change whose COMMIT acknowledgement was lost answers 503 with code tag_change_outcome_unknown (Retry-After): the change MAY have been applied, so never treat it as not applied; read the contact before retrying (a retry of a change that did commit is a reported no-op).";
25
+ export declare const TAG_READ_DEGRADED_NOTE = "When the tag change committed but a response-only read failed, the answer is still 200: `_tagsDegraded` { read: contact_tags, reason: request_budget | read_failed, tagsPredateTagChanges: true } says the `tags` shown are from before the change (tagChanges is what changed), and `_degraded` { read: custom_field_definitions, reason: request_budget | read_failed, customFieldsOmitted: true } says customFields is shown as {} because it was omitted, not because it is empty.";
23
26
  export declare const TAG_FILTER_NOTE = "Filter by tag NAME: one name, or up to 20 distinct names in an array (the contact carries ANY of them). Names match case-insensitively within your account. Cannot be combined with tagId (400). To filter by tag id use tagId.";
24
27
  export declare const TAG_ID_FILTER_NOTE = "Filter by tag ID (uuid): one id, or up to 20 distinct ids in an array (the contact carries ANY of them). A malformed id or more than 20 ids is a 400; an id that is not a tag of your account matches nothing; a merged-away tag id follows its alias to the live tag. Cannot be combined with tag (400). meta.total counts the filtered set when present, but it can be null with total_deferred; per_page 1 is only an existence probe. Use conduyt_count_contacts with tagId for the exact total.";
25
28
  /** (slow566b, app main 9aef66389) the contacts list may not count: how a caller gets the exact total */
@@ -73,6 +73,9 @@ function createMergePreviewStore() {
73
73
  /** (API ?email=, app main 318adf38d) exact lookup of one address; the API trims and lower-cases, so a stray space is harmless */
74
74
  const EMAIL_LOOKUP_ONE = z.string().trim().min(1).max(254);
75
75
  export const EMAIL_LOOKUP_NOTE = "Exact email lookup: one address, or up to 20 distinct addresses in an array. Each is trimmed and lower-cased and matches the contact's primary email OR any secondary email slot (email_2 and up); it is an exact match, not a substring search (use `search` for partial text). Combines with every other filter (AND) inside your account and visibility. An empty or invalid address, or more than 20 distinct addresses, is a 400. On a workspace whose identifier index is still being built, the lookup answers 422 when the stored spellings of the requested addresses exceed its stored-spelling bind budget (a count of spellings, not of contacts; other filters do not help); ask support to complete the identifier backfill. Send addresses once; duplicates collapse.";
76
+ /** (parity65pub, app apigaps65b-r4 8d674129ad) what a tag change answers when its COMMIT outcome is unknown; shared by every tool that changes a contact's tags */
77
+ export const TAG_OUTCOME_UNKNOWN_NOTE = "A tag change whose COMMIT acknowledgement was lost answers 503 with code tag_change_outcome_unknown (Retry-After): the change MAY have been applied, so never treat it as not applied; read the contact before retrying (a retry of a change that did commit is a reported no-op).";
78
+ export const TAG_READ_DEGRADED_NOTE = "When the tag change committed but a response-only read failed, the answer is still 200: `_tagsDegraded` { read: contact_tags, reason: request_budget | read_failed, tagsPredateTagChanges: true } says the `tags` shown are from before the change (tagChanges is what changed), and `_degraded` { read: custom_field_definitions, reason: request_budget | read_failed, customFieldsOmitted: true } says customFields is shown as {} because it was omitted, not because it is empty.";
76
79
  /** (API ?tag= / ?tagId=, #506) both are repeatable and capped at 20 distinct values; the API reads every occurrence (ANY-of) and refuses tagId together with tag */
77
80
  const TAG_FILTER_MAX = 20;
78
81
  export const TAG_FILTER_NOTE = "Filter by tag NAME: one name, or up to 20 distinct names in an array (the contact carries ANY of them). Names match case-insensitively within your account. Cannot be combined with tagId (400). To filter by tag id use tagId.";
@@ -206,7 +209,7 @@ export function registerContactTools(server, client) {
206
209
  created.inputSchema = Object.assign(base.superRefine((v, ctx) => { if (callDerivedFieldsConflict(v))
207
210
  ctx.addIssue({ code: z.ZodIssueCode.custom, message: CALL_DERIVED_REFUSAL, path: ["callId"] }); }), { shape: base.shape });
208
211
  }
209
- strictInput(server.tool("conduyt_update_contact", "Update an existing contact's fields — name, email, phone, company, owner (assignedTo), custom fields. A reassignment releases the previous owner unless keepPreviousOwnerAsCollaborator is true, which keeps them as a collaborator (read-only access to the lead and its cards). customFields merge into existing values (omit a key to leave it unchanged). Pass expectedRevision (the contact's `revision` as you read it) to refuse the save when the contact changed since." + INVALID_NUMBER_REFUSALS + " " + CONTACT_CHANGED + " " + IDENTITY_SAVE_RETRY + " " + FORMULA_WRITE_NOTE + " " + OFF_LIST_NOTE + " " + USER_FIELD_RECORD_WRITE_DOC + REPLY_USERS_DOC, {
212
+ strictInput(server.tool("conduyt_update_contact", "Update an existing contact's fields — name, email, phone, company, owner (assignedTo), custom fields. A reassignment releases the previous owner unless keepPreviousOwnerAsCollaborator is true, which keeps them as a collaborator (read-only access to the lead and its cards). customFields merge into existing values (omit a key to leave it unchanged). Pass expectedRevision (the contact's `revision` as you read it) to refuse the save when the contact changed since. TAGS: change a contact's tags with addTags / removeTags (tag names or ids, at most 100 each; refusals unknown_tag_name 400, unknown_tag_id 422, tag_add_remove_conflict 400 for the same tag in both lists, too_many_tags 400). When either list is sent the answer gains tagChanges { added, removed, unchanged: { alreadyTagged, notTagged } }, so a no-op (a tag already there, a tag not on the contact) is reported rather than silent. PATCH IGNORES a `tags` field (the API answers with a warning): this tool does not take it, use addTags / removeTags. " + TAG_OUTCOME_UNKNOWN_NOTE + " " + TAG_READ_DEGRADED_NOTE + INVALID_NUMBER_REFUSALS + " " + CONTACT_CHANGED + " " + IDENTITY_SAVE_RETRY + " " + FORMULA_WRITE_NOTE + " " + OFF_LIST_NOTE + " " + USER_FIELD_RECORD_WRITE_DOC + REPLY_USERS_DOC, {
210
213
  id: z.string().describe("Contact UUID"),
211
214
  email: z.string().optional().describe("Updated email"),
212
215
  firstName: z.string().optional().describe("Updated first name"),
@@ -220,6 +223,8 @@ export function registerContactTools(server, client) {
220
223
  masterStatus: z.string().trim().min(1).max(40).optional().describe("Lifecycle status of the LEAD (master record), distinct from any deal's status: 'open' (default), 'won', 'lost', 'abandoned', 'disqualified', or an account-defined custom status. A terminal status (won/lost/abandoned/disqualified) SILENCES all outbound automations for this contact — drips, sequences, and scheduled sends stop. Use conduyt_get_lifecycle_settings to see the account's configured statuses."),
221
224
  customFields: z.record(z.any()).optional().describe("Structured custom-field values to merge, keyed by field key. Omit a key to leave it unchanged."),
222
225
  custom_fields: z.record(z.any()).optional().describe("Alias for customFields (snake_case). Provide only one of customFields / custom_fields."),
226
+ addTags: z.array(z.string().min(1)).max(100).optional().describe("Tags to add: tag NAMES or tag ids, at most 100. An unknown name is 400 unknown_tag_name, an unknown id 422 unknown_tag_id, more than 100 in a list 400 too_many_tags, the same tag in addTags and removeTags 400 tag_add_remove_conflict. A tag the contact already has is reported, not an error (tagChanges.unchanged.alreadyTagged)."),
227
+ removeTags: z.array(z.string().min(1)).max(100).optional().describe("Tags to remove: tag NAMES or tag ids, at most 100 (same refusals as addTags). A tag the contact does not carry is reported, not an error (tagChanges.unchanged.notTagged)."),
223
228
  expectedRevision: expectedRevision(),
224
229
  }, async ({ id, customFields, custom_fields, ...updates }) => {
225
230
  const cf = resolveCustomFields(customFields, custom_fields);
@@ -255,9 +260,9 @@ export function registerContactTools(server, client) {
255
260
  const result = await client.del(`/api/v1/contacts/${encodeURIComponent(id)}`);
256
261
  return formatResult(result);
257
262
  });
258
- server.tool("conduyt_add_tags", "Add one or more existing tags to a contact by tag UUID. Tags must already exist (create them with conduyt_create_tag); this does NOT create tags." + REPLY_USERS_DOC, {
263
+ server.tool("conduyt_add_tags", "Add one or more existing tags to a contact by tag name or tag UUID (tagIds takes both, mixed). Tags must already exist (create them with conduyt_create_tag); this does NOT create tags. " + TAG_OUTCOME_UNKNOWN_NOTE + REPLY_USERS_DOC, {
259
264
  contactId: z.string().describe("Contact UUID"),
260
- tagIds: z.array(z.string()).describe("Tag UUIDs to add (must already exist)"),
265
+ tagIds: z.array(z.string()).describe("Tag names or tag UUIDs to add (must already exist)"),
261
266
  }, async ({ contactId, tagIds }) => {
262
267
  const result = await client.post(`/api/v1/contacts/${contactId}/tags`, { tagIds });
263
268
  return formatResult(result);
@@ -63,7 +63,7 @@ function boardSnapshotColumns(a, f) {
63
63
  return a.board_columns.map((c) => (c.limit === undefined ? c.stageId : `${c.stageId}:${c.limit}`)).join(",");
64
64
  }
65
65
  export function registerDealTools(server, client) {
66
- strictInput(server.tool("conduyt_list_deals", "List deals with filtering by pipeline, stage, assignee, or status. Returns deal title, value, stage, contact, and dates. Filter by pipeline/stage NAME (the same names you import with) or by UUID — both camelCase (pipelineName) and snake_case (pipeline_name) argument names are accepted. An unknown name returns a clear error, never the whole account. Each deal row carries hasNextStep (boolean: an open task or a booked appointment from a day ago on; the Needs next action rule's own answer) and nextAppointmentAt (ISO string or null; null unless your key can view the calendar, even when hasNextStep is true). PIPELINE HEALTH: pass health_summary=true to get the Pipeline health strip for the same filtered set instead of the deal list: { totalOpenDeals, atRiskValue, checks[] (key, label, severity, color, rule, count, value; the six checks high_value_idle, stale, unassigned, needs_action, missing_close_date, missing_contact, ordered by money at risk), deals }. Add health_check to also get that check's first page of deals (highest value first) as deals: { check, offset, items, hasMore, nextCursor, total }; deals is null without a check. Page with health_cursor (the previous nextCursor, passed back UNCHANGED: an opaque signed token) or health_offset, and health_rows_only=true to get just the page without the summary: the answer is {data:{deals:{check, offset, items, hasMore, nextCursor}}} (the page sits under data.deals). " + HEALTH_ERRORS + " " + BOARD_SNAPSHOT_DOC + " " + BUSY_503_DOC + MIRROR_READ_DOC + " A mirror key is not filterable (422 mirror_not_filterable). The API judges the query NAMES (batch32, #1313): a name GET /deals does not read is 400 unknown_query_param { message, unknown[], accepted[] (every name it reads), didYouMean { name: accepted twin } for the camelCase / snake_case twin of an accepted name } and is never silently ignored (it used to answer the unfiltered list); two different values for a single-value name (status, contact_id, search, stale, needsAction, summary, latest_updated, system_occupancy, sort, order, page, per_page, value_min / minValue, value_max / maxValue) are 400 query_param_conflict { message, param }, an exact repeat is accepted. This tool sends only accepted names (pipeline, pipeline_name, stage, stage_name, assigned_to, status, include_parked, search, contact_timezone, view_id, page, per_page, sort, order, list_order, board_snapshot, board_columns, health_summary, health_check, health_limit, health_offset, health_cursor, health_rows_only), so these two codes mean an older or newer server than this MCP expects; they reach you as `Conduyt API 400: <message>` with the code. The API judges sort and order (batch32): an unknown sort field, or an order other than asc / desc, is 400 sort_invalid { message, param, accepted } (the sent spelling in param) and is never silently replaced by the default order. The deal value bounds are judged too: value_min / minValue and value_max / maxValue that are non-numeric or outside the deal value column range (-9999999999.99..9999999999.99) are 400 invalid_value_min / invalid_value_max { message, param, accepted } (absent or empty = no filter; an alias spelling answers the same code with the sent spelling in param)." + " " + ROLE_COLUMNS_NOTE + " TIME ZONE (#1312): " + CONTACT_TIMEZONE_NOTE + LIST_USERS_DOC, {
66
+ strictInput(server.tool("conduyt_list_deals", "List deals with filtering by pipeline, stage, assignee, or status. Returns deal title, value, stage, contact, and dates. Paged: meta.has_more says whether another page exists; page by has_more, never by meta.total (the total can be left out). Filter by pipeline/stage NAME (the same names you import with) or by UUID — both camelCase (pipelineName) and snake_case (pipeline_name) argument names are accepted. An unknown name returns a clear error, never the whole account. Each deal row carries hasNextStep (boolean: an open task or a booked appointment from a day ago on; the Needs next action rule's own answer) and nextAppointmentAt (ISO string or null; null unless your key can view the calendar, even when hasNextStep is true). PIPELINE HEALTH: pass health_summary=true to get the Pipeline health strip for the same filtered set instead of the deal list: { totalOpenDeals, atRiskValue, checks[] (key, label, severity, color, rule, count, value; the six checks high_value_idle, stale, unassigned, needs_action, missing_close_date, missing_contact, ordered by money at risk), deals }. Add health_check to also get that check's first page of deals (highest value first) as deals: { check, offset, items, hasMore, nextCursor, total }; deals is null without a check. Page with health_cursor (the previous nextCursor, passed back UNCHANGED: an opaque signed token) or health_offset, and health_rows_only=true to get just the page without the summary: the answer is {data:{deals:{check, offset, items, hasMore, nextCursor}}} (the page sits under data.deals). " + HEALTH_ERRORS + " " + BOARD_SNAPSHOT_DOC + " " + BUSY_503_DOC + MIRROR_READ_DOC + " A mirror key is not filterable (422 mirror_not_filterable). The API judges the query NAMES (batch32, #1313): a name GET /deals does not read is 400 unknown_query_param { message, unknown[], accepted[] (every name it reads), didYouMean { name: accepted twin } for the camelCase / snake_case twin of an accepted name } and is never silently ignored (it used to answer the unfiltered list); two different values for a single-value name (status, contact_id, search, stale, needsAction, summary, latest_updated, system_occupancy, sort, order, page, per_page, value_min / minValue, value_max / maxValue) are 400 query_param_conflict { message, param }, an exact repeat is accepted. This tool sends only accepted names (pipeline, pipeline_name, stage, stage_name, assigned_to, status, include_parked, search, contact_timezone, view_id, page, per_page, sort, order, list_order, board_snapshot, board_columns, health_summary, health_check, health_limit, health_offset, health_cursor, health_rows_only), so these two codes mean an older or newer server than this MCP expects; they reach you as `Conduyt API 400: <message>` with the code. The API judges sort and order (batch32): an unknown sort field, or an order other than asc / desc, is 400 sort_invalid { message, param, accepted } (the sent spelling in param) and is never silently replaced by the default order. The deal value bounds are judged too: value_min / minValue and value_max / maxValue that are non-numeric or outside the deal value column range (-9999999999.99..9999999999.99) are 400 invalid_value_min / invalid_value_max { message, param, accepted } (absent or empty = no filter; an alias spelling answers the same code with the sent spelling in param)." + " " + ROLE_COLUMNS_NOTE + " TIME ZONE (#1312): " + CONTACT_TIMEZONE_NOTE + LIST_USERS_DOC, {
67
67
  pipeline: z.string().optional().describe("Filter by pipeline UUID (canonical). Aliases: pipelineId, pipeline_id."),
68
68
  pipelineId: z.string().optional().describe("Filter by pipeline UUID (alias of pipeline)."),
69
69
  pipeline_id: z.string().optional().describe("snake_case alias of pipelineId."),
@@ -0,0 +1,63 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { ConduytClient } from "../client.js";
3
+ /**
4
+ * (ocr65-parity) The document reader (OCR) on a contact's files: list what was read, start or restart a read, review one read, fill a
5
+ * deal from it (the only write to CRM records, and only when that tool is called), the workspace's document types, and the workspace
6
+ * switch settings.documentReader.enabled. Every reader route answers 404 code document_reader_off while the switch is off.
7
+ * (parity66a, app batch65 5de16149a9: ocr66 / ocr66-autoqueue / ocr66-fillconfirm / ocr65-fillmap) the workspace's reader settings
8
+ * (autoRead, dailyLimit, the cloud-model consent cloudModel; autoReadSince, decidedBy and decidedAt are stamped by the server and
9
+ * never sent), the confirm step of a flagged value (POST /document-reads/{id}/confirm), and a fill-map target's `normalize`.
10
+ *
11
+ * Refusals come back as error results carrying the API's status and code (readerRefusal).
12
+ *
13
+ * Masked values stay masked (defence in depth): the app answers a sensitive value as the Secure mask with sensitive: true and nothing
14
+ * else. These tools do not rely on that alone: any object a response marks sensitive: true leaves the tool as { key, field, label, kind,
15
+ * value: the mask (null when the API gave null), sensitive: true }, never with a quote, page, box, basis, title, confidence or any other
16
+ * key, and a summary tile whose label is a sensitive field's label answers the mask (tiles carry no sensitive flag; the app masks them). The document-type tools carry no read
17
+ * values: they answer only the API's configuration fields (unknown keys are dropped).
18
+ */
19
+ /** the Secure mask the app answers for a sensitive value (lib/custom-field-secure-shared.ts SECURE_MASK) */
20
+ export declare const SECURE_MASK = "\u2022\u2022\u2022\u2022";
21
+ /** every object marked sensitive: true, at any depth, is reduced to maskedEntry */
22
+ export declare function scrubSensitive(v: unknown): unknown;
23
+ export declare function readerRefusal(err: unknown): {
24
+ content: {
25
+ type: "text";
26
+ text: string;
27
+ }[];
28
+ isError: true;
29
+ } | null;
30
+ /** (parity66a, app lib/document-reader/flag.ts) the reader settings' limits and the cloud model providers a workspace can consent to */
31
+ export declare const AUTO_READ_DAILY_LIMIT_DEFAULT = 200;
32
+ export declare const AUTO_READ_DAILY_LIMIT_MAX = 5000;
33
+ export declare const CLOUD_MODEL_PROVIDERS: readonly ["google_gemini"];
34
+ /** the API's own refusal sentences (app/api/v1/settings/route.ts settingsPatchSchema; a 422 with the first one when the body breaks it) */
35
+ export declare const READER_SETTINGS_NEEDS_ONE = "documentReader needs enabled, cloudModel, autoRead or dailyLimit";
36
+ export declare const CLOUD_PROVIDER_REQUIRED = "cloudModel.provider is required when allowed is true";
37
+ /** (app/api/v1/document-reads/[id]/confirm/route.ts, 400 invalid_body) */
38
+ export declare const CONFIRM_FIELD_OR_FIELDS = "body: send either field or fields";
39
+ /**
40
+ * (parity66a) the reader's settings as the server reads them (lib/document-reader/flag.ts): enabled (absent = off), autoRead (absent =
41
+ * on), dailyLimit (absent or out of range = 200), autoReadSince (server-stamped when automatic reading turned on; null = nothing is read
42
+ * automatically yet), cloudModel { allowed (only with a known provider), provider, decidedBy, decidedAt } (who decided and when: set
43
+ * by the server). Only these keys and the settings revision leave the tool.
44
+ */
45
+ export declare function readerSettingsOut(settings: unknown): {
46
+ documentReader: {
47
+ enabled: boolean;
48
+ autoRead: boolean;
49
+ dailyLimit: number;
50
+ autoReadSince: string | null;
51
+ cloudModel: {
52
+ allowed: boolean;
53
+ provider: string | null;
54
+ decidedBy: string | null;
55
+ decidedAt: string | null;
56
+ };
57
+ };
58
+ settingsRevision: string | null;
59
+ };
60
+ /** (Codex parity66a-r1 P2) a stored instant as the server reads it (lib/document-reader/flag.ts autoReadSettings: Date.parse, finite or null);
61
+ * the stored string is answered when it parses, null otherwise */
62
+ export declare function readableInstant(v: unknown): string | null;
63
+ export declare function registerDocumentReaderTools(server: McpServer, client: ConduytClient): void;
@@ -0,0 +1,318 @@
1
+ import { z } from "zod";
2
+ import { ConduytApiError, formatResult, formatToolError } from "../client.js";
3
+ import { strictInput } from "./strict.js";
4
+ /**
5
+ * (ocr65-parity) The document reader (OCR) on a contact's files: list what was read, start or restart a read, review one read, fill a
6
+ * deal from it (the only write to CRM records, and only when that tool is called), the workspace's document types, and the workspace
7
+ * switch settings.documentReader.enabled. Every reader route answers 404 code document_reader_off while the switch is off.
8
+ * (parity66a, app batch65 5de16149a9: ocr66 / ocr66-autoqueue / ocr66-fillconfirm / ocr65-fillmap) the workspace's reader settings
9
+ * (autoRead, dailyLimit, the cloud-model consent cloudModel; autoReadSince, decidedBy and decidedAt are stamped by the server and
10
+ * never sent), the confirm step of a flagged value (POST /document-reads/{id}/confirm), and a fill-map target's `normalize`.
11
+ *
12
+ * Refusals come back as error results carrying the API's status and code (readerRefusal).
13
+ *
14
+ * Masked values stay masked (defence in depth): the app answers a sensitive value as the Secure mask with sensitive: true and nothing
15
+ * else. These tools do not rely on that alone: any object a response marks sensitive: true leaves the tool as { key, field, label, kind,
16
+ * value: the mask (null when the API gave null), sensitive: true }, never with a quote, page, box, basis, title, confidence or any other
17
+ * key, and a summary tile whose label is a sensitive field's label answers the mask (tiles carry no sensitive flag; the app masks them). The document-type tools carry no read
18
+ * values: they answer only the API's configuration fields (unknown keys are dropped).
19
+ */
20
+ /** the Secure mask the app answers for a sensitive value (lib/custom-field-secure-shared.ts SECURE_MASK) */
21
+ export const SECURE_MASK = "••••";
22
+ const DOCUMENT_READER_OFF_SENTENCE = "The document reader is switched off for this workspace (settings.documentReader.enabled is off): nothing was read or written. An owner or admin can switch it on with conduyt_update_document_reader_enabled.";
23
+ const CREDITOR_ROW_EXISTS_SENTENCE = "This contact's creditor table already has a row matching this document (existingRow): nothing was filled. Show the existing row; nothing is written unless a person decides to change it.";
24
+ const str = (v) => (typeof v === "string" ? v : undefined);
25
+ const isRecord = (v) => !!v && typeof v === "object" && !Array.isArray(v);
26
+ /** a value marked sensitive: only its identity and the mask (or null) leave the tool */
27
+ function maskedEntry(o) {
28
+ const out = {};
29
+ for (const k of ["key", "field", "label", "kind"])
30
+ if (typeof o[k] === "string")
31
+ out[k] = o[k];
32
+ out.value = o.value === null || o.value === undefined ? null : SECURE_MASK;
33
+ out.sensitive = true;
34
+ return out;
35
+ }
36
+ /** every object marked sensitive: true, at any depth, is reduced to maskedEntry */
37
+ export function scrubSensitive(v) {
38
+ if (Array.isArray(v))
39
+ return v.map(scrubSensitive);
40
+ if (isRecord(v)) {
41
+ if (v.sensitive === true)
42
+ return maskedEntry(v);
43
+ return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, scrubSensitive(x)]));
44
+ }
45
+ return v;
46
+ }
47
+ /** a read (the review, or a file row's read): the app masks tiles itself and tiles carry no sensitive flag (none is added here); a tile
48
+ * labelled like a sensitive field of the same read is answered { label, value: the mask or null } all the same */
49
+ function maskRead(read) {
50
+ if (!isRecord(read))
51
+ return scrubSensitive(read);
52
+ const fields = Array.isArray(read.fields) ? read.fields.filter(isRecord) : [];
53
+ const sensitiveLabels = new Set(fields.filter((f) => f.sensitive === true && f.kind !== "clause" && typeof f.label === "string").map((f) => f.label));
54
+ const tiles = Array.isArray(read.tiles)
55
+ ? read.tiles.map((t) => (isRecord(t) && typeof t.label === "string" && sensitiveLabels.has(t.label) ? { label: t.label, value: t.value === null || t.value === undefined ? null : SECURE_MASK } : t))
56
+ : read.tiles;
57
+ return scrubSensitive(read.tiles === undefined ? read : { ...read, tiles });
58
+ }
59
+ /** the answer's `data` envelope, each read in it masked; the whole envelope (siblings of `data` included) passes the scrub (Codex r1 P3) */
60
+ function maskedReview(answer) {
61
+ if (isRecord(answer) && "data" in answer)
62
+ return scrubSensitive({ ...answer, data: maskRead(answer.data) });
63
+ return maskRead(answer);
64
+ }
65
+ function maskedFileList(answer) {
66
+ const data = isRecord(answer) ? answer.data : undefined;
67
+ if (!isRecord(data) || !Array.isArray(data.files))
68
+ return scrubSensitive(answer);
69
+ const files = data.files.map((f) => (isRecord(f) && "read" in f ? { ...f, read: maskRead(f.read) } : f));
70
+ return scrubSensitive({ ...answer, data: { ...data, files } });
71
+ }
72
+ /**
73
+ * An API refusal as a structured error result: { ok: false, status, code?, error: a plain sentence, apiError, ...the refusal's other
74
+ * details (existingRow, skipped, written, step, reason), retryAfterSeconds? }. The details pass the same sensitive scrub; the raw error
75
+ * line is included only when it carries no details object. Transport failures (timeout, network) are thrown as they are.
76
+ */
77
+ /** the client's error line `Conduyt API <status>: <error>[ [Retry-After: Ns]][ <details JSON>]` split into the API's words and the
78
+ * details object (the final token: each `{` from the left is tried until the rest parses) */
79
+ function splitRefusal(message) {
80
+ let details = null;
81
+ let head = message;
82
+ for (let i = message.indexOf("{"); i !== -1; i = message.indexOf("{", i + 1)) {
83
+ try {
84
+ const v = JSON.parse(message.slice(i));
85
+ if (isRecord(v)) {
86
+ details = v;
87
+ head = message.slice(0, i);
88
+ break;
89
+ }
90
+ }
91
+ catch { /* not the details object: try the next brace */ }
92
+ }
93
+ const words = head.replace(/^Conduyt API \d+:\s*/, "").replace(/\s*\[Retry-After: [^\]]*\]\s*$/, "").trim();
94
+ return { apiError: words || null, details };
95
+ }
96
+ export function readerRefusal(err) {
97
+ if (!(err instanceof ConduytApiError) || err.code !== "http")
98
+ return null;
99
+ const { apiError, details } = splitRefusal(err.message);
100
+ const code = typeof details?.code === "string" ? details.code : null;
101
+ const sentence = code === "document_reader_off" ? DOCUMENT_READER_OFF_SENTENCE : code === "creditor_row_exists" ? CREDITOR_ROW_EXISTS_SENTENCE : apiError ?? `Conduyt API ${err.status}`;
102
+ // a fill_failed / fill_partial body carries the refused step's own HTTP status as `status`: kept as stepStatus, never replacing the answer's
103
+ const rest = details ? Object.fromEntries(Object.entries(details).filter(([k]) => k !== "code" && k !== "error" && k !== "ok").map(([k, v]) => [k === "status" ? "stepStatus" : k, v])) : {};
104
+ const body = {
105
+ ok: false,
106
+ status: err.status,
107
+ ...(code ? { code } : {}),
108
+ error: sentence,
109
+ ...(apiError && apiError !== sentence ? { apiError } : {}),
110
+ ...scrubSensitive(rest),
111
+ ...(err.retryAfterSeconds !== null ? { retryAfterSeconds: err.retryAfterSeconds } : {}),
112
+ ...(details ? {} : { message: err.message.slice(0, 500) }),
113
+ };
114
+ const base = formatToolError(sentence);
115
+ return { ...base, content: [{ type: "text", text: JSON.stringify(body, null, 2) }] };
116
+ }
117
+ async function guarded(call) {
118
+ try {
119
+ return await call();
120
+ }
121
+ catch (err) {
122
+ const refusal = readerRefusal(err);
123
+ if (refusal)
124
+ return refusal;
125
+ throw err;
126
+ }
127
+ }
128
+ // ---- the document types: configuration only, answered field by field ----
129
+ const FIELD_KEY = /^[a-z][a-z0-9_]{0,59}$/;
130
+ const TYPE_KEY = /^[a-z][a-z0-9_]{0,39}$/;
131
+ const CREDITOR_PATTERN = /^creditor_\{n\}(_[a-z0-9_]{1,40})?$/;
132
+ const typeFieldSchema = z
133
+ .object({
134
+ key: z.string().regex(FIELD_KEY).describe("lower case letters, digits and _, starting with a letter (at most 60)"),
135
+ label: z.string().trim().min(1).max(80),
136
+ kind: z.enum(["stated", "worked_out", "clause"]).optional().describe("stated (read from the words, the default), worked_out (calculated; the review says from what) or clause (flagged, never filled)"),
137
+ sensitive: z.boolean().optional().describe("true for an SSN, tax ID or bank detail: stored encrypted, answered masked, filled only into a Secure field (default false)"),
138
+ tile: z.boolean().optional().describe("shown as one of the summary tiles (at most three per type; default false)"),
139
+ rowKey: z.boolean().optional().describe("identifies a creditor-table row together with the type's other rowKey fields: a fill whose rowKey values all match an existing row adds nothing (409 creditor_row_exists; default false)"),
140
+ })
141
+ .strict();
142
+ /** (ocr65-fillmap, app lib/document-reader/types.ts normalizeSchema) how a value is put into the form its target reads */
143
+ const NORMALIZE = ["payment_frequency"];
144
+ const normalizeSchema = z.enum(NORMALIZE).optional().describe("payment_frequency: the value is read as a payment frequency and written as its label (Daily, Weekly, Bi-Weekly, Semi-Monthly, Monthly); a frequency it does not know is not filled");
145
+ const fillTargetSchema = z.union([
146
+ z.object({ kind: z.literal("deal_field"), key: z.string().regex(FIELD_KEY).describe("the deal custom field key"), normalize: normalizeSchema }).strict(),
147
+ z.object({ kind: z.literal("creditor_column"), pattern: z.string().regex(CREDITOR_PATTERN).describe("a creditor_{n} pattern: a column of the creditor table such as creditor_{n}_balance, or a field of the slot the table does not show"), normalize: normalizeSchema }).strict(),
148
+ ]);
149
+ const documentTypeSchema = z
150
+ .object({
151
+ key: z.string().regex(TYPE_KEY).describe("1 to 40 lower case letters, digits and _, starting with a letter; unique"),
152
+ label: z.string().trim().min(1).max(80),
153
+ status: z.enum(["active", "planned"]).optional().describe("active (read; the default) or planned (recognised, not read: the file waits; a planned type fills nothing)"),
154
+ fields: z.array(typeFieldSchema).max(60).optional(),
155
+ fillMap: z.array(z.object({ field: z.string().regex(FIELD_KEY), target: fillTargetSchema }).strict()).max(60).optional().describe("which field goes where on a deal: never a clause, never the creditor table's Enroll column, never two fields into one target"),
156
+ })
157
+ .strict();
158
+ function typeOut(t) {
159
+ if (!isRecord(t))
160
+ return null;
161
+ const fields = Array.isArray(t.fields)
162
+ ? t.fields.filter(isRecord).map((f) => ({ key: str(f.key), label: str(f.label), kind: str(f.kind), sensitive: f.sensitive === true, tile: f.tile === true, rowKey: f.rowKey === true }))
163
+ : [];
164
+ const fillMap = Array.isArray(t.fillMap)
165
+ ? t.fillMap.filter(isRecord).map((m) => {
166
+ const target = isRecord(m.target) ? m.target : {};
167
+ // (parity66a) normalize kept only as one of the API's values, so a types read sent back unchanged keeps it
168
+ const normalize = NORMALIZE.includes(target.normalize) ? { normalize: target.normalize } : {};
169
+ return { field: str(m.field), target: target.kind === "creditor_column" ? { kind: "creditor_column", pattern: str(target.pattern), ...normalize } : { kind: str(target.kind), key: str(target.key), ...normalize } };
170
+ })
171
+ : [];
172
+ return { key: str(t.key), label: str(t.label), status: str(t.status), fields, fillMap };
173
+ }
174
+ /** the types answer, field by field: { data: { builtIn, types } } and nothing else */
175
+ function typesOut(answer) {
176
+ const data = isRecord(answer) && isRecord(answer.data) ? answer.data : {};
177
+ return { data: { builtIn: data.builtIn === true, types: Array.isArray(data.types) ? data.types.map(typeOut) : [] } };
178
+ }
179
+ /** the switch's answer: only the switch and the revision of the settings it was saved at */
180
+ function switchOut(settings) {
181
+ const s = isRecord(settings) ? settings : {};
182
+ const block = isRecord(s.documentReader) ? s.documentReader : {};
183
+ return { documentReader: { enabled: block.enabled === true }, settingsRevision: typeof s.settingsRevision === "string" ? s.settingsRevision : null };
184
+ }
185
+ /** (parity66a, app lib/document-reader/flag.ts) the reader settings' limits and the cloud model providers a workspace can consent to */
186
+ export const AUTO_READ_DAILY_LIMIT_DEFAULT = 200;
187
+ export const AUTO_READ_DAILY_LIMIT_MAX = 5000;
188
+ export const CLOUD_MODEL_PROVIDERS = ["google_gemini"];
189
+ /** the API's own refusal sentences (app/api/v1/settings/route.ts settingsPatchSchema; a 422 with the first one when the body breaks it) */
190
+ export const READER_SETTINGS_NEEDS_ONE = "documentReader needs enabled, cloudModel, autoRead or dailyLimit";
191
+ export const CLOUD_PROVIDER_REQUIRED = "cloudModel.provider is required when allowed is true";
192
+ /** (app/api/v1/document-reads/[id]/confirm/route.ts, 400 invalid_body) */
193
+ export const CONFIRM_FIELD_OR_FIELDS = "body: send either field or fields";
194
+ /**
195
+ * (parity66a) the reader's settings as the server reads them (lib/document-reader/flag.ts): enabled (absent = off), autoRead (absent =
196
+ * on), dailyLimit (absent or out of range = 200), autoReadSince (server-stamped when automatic reading turned on; null = nothing is read
197
+ * automatically yet), cloudModel { allowed (only with a known provider), provider, decidedBy, decidedAt } (who decided and when: set
198
+ * by the server). Only these keys and the settings revision leave the tool.
199
+ */
200
+ export function readerSettingsOut(settings) {
201
+ const s = isRecord(settings) ? settings : {};
202
+ const b = isRecord(s.documentReader) ? s.documentReader : {};
203
+ const limit = b.dailyLimit;
204
+ const c = isRecord(b.cloudModel) ? b.cloudModel : {};
205
+ const provider = CLOUD_MODEL_PROVIDERS.includes(c.provider) ? c.provider : null;
206
+ return {
207
+ documentReader: {
208
+ enabled: b.enabled === true,
209
+ autoRead: b.autoRead !== false,
210
+ dailyLimit: typeof limit === "number" && Number.isInteger(limit) && limit >= 1 && limit <= AUTO_READ_DAILY_LIMIT_MAX ? limit : AUTO_READ_DAILY_LIMIT_DEFAULT,
211
+ // (Codex parity66a-r1 P2) as autoReadSettings reads it: a string Date.parse cannot read is null (nothing is read automatically)
212
+ autoReadSince: readableInstant(b.autoReadSince),
213
+ cloudModel: { allowed: c.allowed === true && provider !== null, provider, decidedBy: str(c.decidedBy) ?? null, decidedAt: str(c.decidedAt) ?? null },
214
+ },
215
+ settingsRevision: typeof s.settingsRevision === "string" ? s.settingsRevision : null,
216
+ };
217
+ }
218
+ /** (Codex parity66a-r1 P2) a stored instant as the server reads it (lib/document-reader/flag.ts autoReadSettings: Date.parse, finite or null);
219
+ * the stored string is answered when it parses, null otherwise */
220
+ export function readableInstant(v) {
221
+ return typeof v === "string" && Number.isFinite(Date.parse(v)) ? v : null;
222
+ }
223
+ /** a refusal the tool makes itself, before any request: the API's own sentence, nothing sent */
224
+ function localRefusal(sentence) {
225
+ const base = formatToolError(sentence);
226
+ return { ...base, content: [{ type: "text", text: JSON.stringify({ ok: false, error: sentence, sent: false }, null, 2) }] };
227
+ }
228
+ /** (app fable/ocr65-parity c3ad06e80d, lib/api-key-scopes.ts) the reader's key rules beside each route's own scopes */
229
+ const KEY_RULES = " A legacy unrestricted (empty-scope) API key is refused on every reader route; the key's tier still applies.";
230
+ const SCOPES_FILES = "API key scopes: files." + KEY_RULES;
231
+ export function registerDocumentReaderTools(server, client) {
232
+ strictInput(server.tool("conduyt_list_contact_document_reads", "List a contact's files (its own and its deals' files, as the contact's Files list) with what the document reader did with each (GET /api/v1/contacts/{id}/document-reads). Each file: fileId, fileName, contentType, fileSize, createdAt, uploader, source (contact, or the deal it is on), downloadUrl, and read: null (not read) or { id (the document read id for conduyt_get_document_read / conduyt_fill_deal_from_document_read), status (checking, reading, read, skipped, waiting, failed), waitingReason (not_connected, type_not_available, or daily_limit: an automatic read paused by the workspace's daily limit), errorCode (failed: why; skipped: not_a_document when the file is not a PDF, PNG or JPEG), auto (true = read automatically when the file landed), typeKey, typeLabel, progress, queueAhead, queueBehind, tiles (summary values; a sensitive one is the mask), flags (clause titles with tone), fillable / fillableContact (labels mapped and stated; conduyt_get_document_read fillPreview says which a fill writes), filled (where an earlier fill wrote, labels only) }. Also the workspace's types and readCount. Read only: nothing is queued or written. Refusals: 404 code document_reader_off while the workspace switch is off; 404 unknown contact; 403 missing permission (files:view and contacts:view). API key scopes: contacts + files (a contacts-only key does not reach it)." + KEY_RULES, {
233
+ contactId: z.string().uuid().describe("Contact UUID"),
234
+ }, async ({ contactId }) => guarded(async () => formatResult(maskedFileList(await client.get(`/api/v1/contacts/${encodeURIComponent(contactId)}/document-reads`))))));
235
+ strictInput(server.tool("conduyt_start_document_read", "Start or restart the document reader on one file of a contact or of one of its deals (POST /api/v1/document-reads, body { fileId }): \"Read with Conduyt\" / \"Read again\". A new file is read automatically when it lands while automatic reading is on (conduyt_get_document_reader_settings); this is a person's re-read and never counts against the automatic daily limit. Answers 202 { id, fileId, status, attempt }; the reading runs after the answer, so poll conduyt_get_document_read (or the contact list) for the result. A file already read as an active type restarts at reading; anything else goes back through the type check. RESTARTING DISCARDS the file's earlier reading and its Filled mark (values already written to a deal stay as they are). Nothing is written to a deal. Refusals: 404 code document_reader_off while the workspace switch is off; 404 unknown or hidden file; 409 document_read_busy while the file is being checked or read; 403 code auto_read_paused (the file's automatic read is paused by the daily limit: it is read automatically the next day, and only an owner or admin can read it now); 429 rate limited (60 a minute); 403 missing permission (files:create, files:view, contacts:view). " + SCOPES_FILES, {
236
+ fileId: z.string().uuid().describe("The file's UUID (fileId from conduyt_list_contact_document_reads)"),
237
+ }, async ({ fileId }) => guarded(async () => formatResult(scrubSensitive(await client.post("/api/v1/document-reads", { fileId }))))));
238
+ strictInput(server.tool("conduyt_get_document_read", "Review one document read (GET /api/v1/document-reads/{id}): status, waitingReason, contactId, the file, its type, progress, tiles, flags, fillPreview (one item per mapped field the document states: { field, label, fills, message (null when it fills, else the plain reason), needsCheck (true only on a value the reader flagged for a check), confirmed (only with needsCheck: a person confirmed THIS value of this read attempt) }), fillable and fillableContact (the labels a fill WRITES; fillableContact = those that land on the CONTACT's creditor table, shown on every deal of the contact), filled (where an earlier fill wrote, labels only), and fields: every field of the type with value (null = not stated), quote (the exact source words), page, box (x, y, width, height as page fractions), basis (what a worked-out value was calculated from), confidence, check (true below 85: verify it), tone (a clause), sensitive, and on a flagged value that is not masked reasons (the engine's reason codes, e.g. reads_disagree) and alternative (the other reading). A flagged value is filled only once confirmed (conduyt_confirm_document_read_values). A SENSITIVE field (an SSN, tax ID or bank detail) is answered as the mask with sensitive: true and NO quote, page, box, basis, title, confidence, reasons or alternative: the value is never shown, here or anywhere. Read only. Refusals: 404 code document_reader_off while the workspace switch is off; 404 unknown or hidden read; 403 missing permission (files:view, contacts:view). " + SCOPES_FILES, {
239
+ id: z.string().uuid().describe("The document read id (read.id from conduyt_list_contact_document_reads, or id from conduyt_start_document_read)"),
240
+ }, async ({ id }) => guarded(async () => formatResult(maskedReview(await client.get(`/api/v1/document-reads/${encodeURIComponent(id)}`))))));
241
+ strictInput(server.tool("conduyt_fill_deal_from_document_read", "Fill one deal's fields from a document read (POST /api/v1/document-reads/{id}/fill, body { dealId }): the document reader's ONLY write to CRM records. It writes ONLY when this tool is called, and only to the deal named; NOTHING is ever filled automatically. The workspace's fill map for the document's type decides what goes where: deal_field values into that deal's custom fields, creditor_column values as ONE new row of the creditor table (that table is the CONTACT's record, shown on every deal of the contact). A value the document does not state is never written; a sensitive value goes only into a Secure field. Answers { id, filled { dealId, dealTitle, deal, contact, creditorRow }, filledLabels, written { creditorRow, dealFields }, skipped [{ field, label, reason, message }] } (labels only, never values). Refusals: 409 code confirmation_required with fields [{ field, label }] (a value the reader flagged for a check that this fill would write is not confirmed for its current value: NOTHING was written; show the values, and after a person checks them call conduyt_confirm_document_read_values, then fill again); 409 code creditor_row_exists with existingRow { slot, values } (the contact's creditor table already has this document's row: nothing was filled; show that row); 409 nothing_to_fill; 409 fill_failed / fill_partial (a write was refused: step, reason and what was written are listed); 409 document_not_read; 409 document_type_not_active; 400 deal_not_on_contact (the deal is not one of the read's contact's deals); 404 code document_reader_off while the workspace switch is off; 404 unknown read or deal; 403 missing permission (deals:edit, files:view, contacts:view). API key scopes: files + deals + contacts." + KEY_RULES, {
242
+ id: z.string().uuid().describe("The document read id (status read)"),
243
+ dealId: z.string().uuid().describe("The deal to fill: one of the read's contact's deals (closed ones included)"),
244
+ }, async ({ id, dealId }) => guarded(async () => formatResult(scrubSensitive(await client.post(`/api/v1/document-reads/${encodeURIComponent(id)}/fill`, { dealId }))))));
245
+ strictInput(server.tool("conduyt_get_document_reader_types", "Read the document types the reader knows in this workspace (GET /api/v1/settings/document-reader-types): { builtIn, types: [{ key, label, status (active | planned), fields [{ key, label, kind (stated | worked_out | clause), sensitive, tile, rowKey }], fillMap [{ field, target: { kind: deal_field, key, normalize? } | { kind: creditor_column, pattern, normalize? } }] }] }. builtIn true = the workspace never saved its own types and answers the built-in templates, which fill nothing until the workspace maps them (conduyt_put_document_reader_types). Configuration only: no read values. Refusals: 404 code document_reader_off while the workspace switch is off; 403 missing permission (settings:view). API key scopes: settings.", {}, async () => guarded(async () => formatResult(typesOut(await client.get("/api/v1/settings/document-reader-types"))))));
246
+ strictInput(server.tool("conduyt_put_document_reader_types", "REPLACE the workspace's document types (PUT /api/v1/settings/document-reader-types, body { types }; owner or admin only). The list sent becomes the whole list (types not sent are removed); types: [] returns the workspace to the built-in templates. At most 20 types of at most 60 fields; type keys and field keys unique; at most three tiles per type; a fill map names fields of its own type, never a clause, never the creditor table's Enroll column, never two fields into one target; a planned type fills nothing. A target may carry normalize: payment_frequency (written as Daily, Weekly, Bi-Weekly, Semi-Monthly or Monthly). Read the current list first with conduyt_get_document_reader_types and send it back changed. Answers the saved { builtIn, types }. Nothing is filled or read by this call. Refusals: 422 code invalid_document_types with the first problem; 403 forbidden (not an owner or admin); 413 body_too_large (256 KB); 404 code document_reader_off while the workspace switch is off. API key scopes: settings.", {
247
+ types: z.array(documentTypeSchema).max(20).describe("The complete list of document types ([] = back to the built-in templates)"),
248
+ }, async ({ types }) => guarded(async () => formatResult(typesOut(await client.put("/api/v1/settings/document-reader-types", { types }))))));
249
+ strictInput(server.tool("conduyt_update_document_reader_enabled", "Switch the document reader on or off for this workspace (settings.documentReader.enabled, PATCH /api/v1/settings; owner or admin only). On: the contact page shows the reader, and files that land in a contact's or its deals' Files are read; the reader tools above work. Off (the default): every reader route answers 404 code document_reader_off and nothing new is read; readings already stored are kept. The switch never fills a deal. Answers { documentReader: { enabled }, settingsRevision }. The tool reads the settings revision first and saves against it; a stale revision (another save landed first) is handed back as a conflict with the current switch. Refusals: 403 forbidden (not an owner or admin). API key scopes: settings.", {
250
+ enabled: z.boolean().describe("true = switch the document reader on; false = off"),
251
+ }, async ({ enabled }) => guarded(async () => {
252
+ const read = (await client.get("/api/v1/settings"));
253
+ const expectedSettingsRevision = typeof read?.data?.settingsRevision === "string" ? read.data.settingsRevision : null;
254
+ try {
255
+ const saved = (await client.patch("/api/v1/settings", { documentReader: { enabled }, ...(expectedSettingsRevision ? { expectedSettingsRevision } : {}) }));
256
+ return formatResult({ data: switchOut(saved?.data) });
257
+ }
258
+ catch (err) {
259
+ if (!(err instanceof ConduytApiError && err.status === 409))
260
+ throw err;
261
+ const current = (await client.get("/api/v1/settings"));
262
+ const sentence = "The account settings changed since their revision was read: nothing was saved. Check `current` and call again.";
263
+ const base = formatToolError(sentence);
264
+ return { ...base, content: [{ type: "text", text: JSON.stringify({ ok: false, status: 409, conflict: true, error: sentence, expectedSettingsRevision, current: switchOut(current?.data) }, null, 2) }] };
265
+ }
266
+ })));
267
+ // ---- (parity66a, app batch65 5de16149a9) the reader's workspace settings and the confirm step ----
268
+ strictInput(server.tool("conduyt_get_document_reader_settings", `Read the document reader's workspace settings (GET /api/v1/settings, the documentReader block; read only): { documentReader: { enabled (the switch; absent = off), autoRead (read every new contact or deal file automatically as it lands: upload, inbound e-mail attachment, booking documents; absent = on once the reader is on), dailyLimit (at most this many automatic reads a day in the workspace's time zone; past it a new file waits, paused (waitingReason daily_limit), until the next day or an owner's or admin's read; absent = ${AUTO_READ_DAILY_LIMIT_DEFAULT}), autoReadSince (set by the server when automatic reading turned on: only files that landed from then on are read automatically, never a backfill; null = nothing is read automatically yet), cloudModel { allowed (whether the reading engine may send this workspace's documents to the cloud model named in provider; absent = not allowed: nothing goes to a cloud model), provider (${CLOUD_MODEL_PROVIDERS.join(" | ")} or null), decidedBy (the user id who decided), decidedAt } }, settingsRevision }. Values are as the server reads them. Change them with conduyt_update_document_reader_settings. API key scopes: settings.`, {}, async () => guarded(async () => formatResult({ data: readerSettingsOut((await client.get("/api/v1/settings"))?.data) }))));
269
+ strictInput(server.tool("conduyt_update_document_reader_settings", `Change the document reader's workspace settings (PATCH /api/v1/settings { documentReader: { ... } }; owner or admin only, else 403 forbidden). Send at least one of enabled, autoRead, dailyLimit, cloudModel (else the API's own refusal "${READER_SETTINGS_NEEDS_ONE}", nothing sent); only the keys sent change. enabled: the switch (as conduyt_update_document_reader_enabled). autoRead: read every new contact or deal file automatically as it lands (default on once the reader is on); turning automatic reading on stamps autoReadSince on the server, so files that landed before are never read automatically. dailyLimit: an integer 1 to ${AUTO_READ_DAILY_LIMIT_MAX} (default ${AUTO_READ_DAILY_LIMIT_DEFAULT}) automatic reads a day. cloudModel { allowed, provider }: the workspace's consent to let the reading engine send its documents to a cloud model; provider (${CLOUD_MODEL_PROVIDERS.join(" | ")}) is required when allowed is true ("${CLOUD_PROVIDER_REQUIRED}"); allowed false withdraws it. autoReadSince, decidedBy and decidedAt are set by the server and cannot be sent (the API refuses an unknown key; so does this tool). Nothing is read, filled or deleted by this call. Answers { documentReader: { enabled, autoRead, dailyLimit, autoReadSince, cloudModel { allowed, provider, decidedBy, decidedAt } }, settingsRevision } from the saved settings. The tool reads the settings revision first and saves against it; a stale revision (another save landed first) is handed back as a conflict with the current reader settings. Refusals: 403 forbidden (not an owner or admin); 422 with the API's sentence (a value it refuses). API key scopes: settings.`, {
270
+ enabled: z.boolean().optional().describe("true = the document reader on; false = off"),
271
+ autoRead: z.boolean().optional().describe("true = read every new contact or deal file automatically as it lands; false = only when a person starts a read"),
272
+ dailyLimit: z.number().int().min(1).max(AUTO_READ_DAILY_LIMIT_MAX).optional().describe(`at most this many automatic reads a day (1 to ${AUTO_READ_DAILY_LIMIT_MAX}; default ${AUTO_READ_DAILY_LIMIT_DEFAULT})`),
273
+ cloudModel: z
274
+ .object({
275
+ allowed: z.boolean().describe("whether the reading engine may send this workspace's documents to the cloud model named in provider"),
276
+ provider: z.enum(CLOUD_MODEL_PROVIDERS).optional().describe("the cloud model provider allowed (required when allowed is true)"),
277
+ })
278
+ .strict()
279
+ .refine((c) => !c.allowed || c.provider !== undefined, { message: CLOUD_PROVIDER_REQUIRED })
280
+ .optional()
281
+ .describe("the workspace's cloud-model consent; the server records who decided it and when"),
282
+ }, async ({ enabled, autoRead, dailyLimit, cloudModel }) => guarded(async () => {
283
+ if (enabled === undefined && autoRead === undefined && dailyLimit === undefined && cloudModel === undefined)
284
+ return localRefusal(READER_SETTINGS_NEEDS_ONE);
285
+ if (cloudModel && cloudModel.allowed && cloudModel.provider === undefined)
286
+ return localRefusal(CLOUD_PROVIDER_REQUIRED);
287
+ const documentReader = {
288
+ ...(enabled !== undefined ? { enabled } : {}),
289
+ ...(autoRead !== undefined ? { autoRead } : {}),
290
+ ...(dailyLimit !== undefined ? { dailyLimit } : {}),
291
+ ...(cloudModel !== undefined ? { cloudModel: { allowed: cloudModel.allowed, ...(cloudModel.provider !== undefined ? { provider: cloudModel.provider } : {}) } } : {}),
292
+ };
293
+ const read = (await client.get("/api/v1/settings"));
294
+ const expectedSettingsRevision = typeof read?.data?.settingsRevision === "string" ? read.data.settingsRevision : null;
295
+ try {
296
+ const saved = (await client.patch("/api/v1/settings", { documentReader, ...(expectedSettingsRevision ? { expectedSettingsRevision } : {}) }));
297
+ return formatResult({ data: readerSettingsOut(saved?.data) });
298
+ }
299
+ catch (err) {
300
+ if (!(err instanceof ConduytApiError && err.status === 409))
301
+ throw err;
302
+ const current = (await client.get("/api/v1/settings"));
303
+ const sentence = "The account settings changed since their revision was read: nothing was saved. Check `current` and call again.";
304
+ const base = formatToolError(sentence);
305
+ return { ...base, content: [{ type: "text", text: JSON.stringify({ ok: false, status: 409, conflict: true, error: sentence, expectedSettingsRevision, current: readerSettingsOut(current?.data) }, null, 2) }] };
306
+ }
307
+ })));
308
+ strictInput(server.tool("conduyt_confirm_document_read_values", "Confirm (or take back) values the document reader flagged for a check (POST /api/v1/document-reads/{id}/confirm, body { field } or { fields }, plus confirmed): a value the engine marked, or read with a confidence below 85, shows in conduyt_get_document_read fillPreview with needsCheck true, and conduyt_fill_deal_from_document_read writes it only once a person confirmed THAT value (else 409 confirmation_required). Call this only after a person checked the value against the document. Send exactly one of field (one field key) or fields (a list of 1 to 60 keys); else the API's own refusal \"" + CONFIRM_FIELD_OR_FIELDS + "\", nothing sent. confirmed: true (the default) confirms, false takes the confirmation back. Each confirmation is recorded with who and when and is bound to the read, its attempt and the value as read, so reading the file again or a different value voids it. Nothing is written to a deal or contact. Answers { id, confirmed: [the field keys now confirmed for their current value, in the type's order] }. Refusals: 400 code unknown_field (not a value field of the document's type; a clause is never filled) or invalid_body; 409 code field_not_stated (the document does not state that value), document_not_read, document_type_not_active, read_changed (the file was read again meanwhile: nothing recorded, review it again); 404 code document_reader_off while the workspace switch is off; 404 unknown or hidden read; 403 missing permission (files:view, contacts:view). " + SCOPES_FILES, {
309
+ id: z.string().uuid().describe("The document read id"),
310
+ field: z.string().min(1).max(60).optional().describe("one field key (the key of a fillPreview item / field); send this or fields"),
311
+ fields: z.array(z.string().min(1).max(60)).min(1).max(60).optional().describe("several field keys; send this or field"),
312
+ confirmed: z.boolean().optional().describe("true (the API's default) = confirm; false = take the confirmation back"),
313
+ }, async ({ id, field, fields, confirmed }) => guarded(async () => {
314
+ if ((field === undefined) === (fields === undefined))
315
+ return localRefusal(CONFIRM_FIELD_OR_FIELDS);
316
+ return formatResult(scrubSensitive(await client.post(`/api/v1/document-reads/${encodeURIComponent(id)}/confirm`, { ...(field !== undefined ? { field } : { fields }), ...(confirmed !== undefined ? { confirmed } : {}) })));
317
+ })));
318
+ }
@@ -21,7 +21,7 @@ export function assertOptOutEmail(raw) {
21
21
  return raw;
22
22
  }
23
23
  export function registerEmailOptOutTools(server, client) {
24
- strictInput(server.tool("conduyt_list_email_opt_outs", "List the workspace's email opt-out list (GET /api/v1/email/opt-out-list; owner / admin key), newest first. The list is hash-only, so no address is returned: each row is { id, source, reason, createdAt } where source says how the address got there ('manual' = added by hand with conduyt_add_email_opt_out; other values are an unsubscribe link, an address-confirmed unsubscribe or a Mailchimp sync) and reason is the note recorded. Paged: page (default 1) and perPage (1-100, default 25); the answer carries meta { page, perPage, total, totalPages }. Every customer-facing email send (campaigns, sequences, one-off, automation, transactional and booking mail) refuses a listed address. 403 for a non-admin key is surfaced verbatim.", {
24
+ strictInput(server.tool("conduyt_list_email_opt_outs", "List the workspace's email opt-out list (GET /api/v1/email/opt-out-list; owner / admin key), newest first. The list is hash-only, so no address is returned: each row is { id, source, reason, createdAt } where source says how the address got there ('manual' = added by hand with conduyt_add_email_opt_out; other values are an unsubscribe link, an address-confirmed unsubscribe or a Mailchimp sync) and reason is the note recorded. Paged: page (default 1) and perPage (1-100, default 25); the answer carries meta { page, perPage, total, totalPages, has_more }. Page by has_more (keep going while it is true), never by total: a total can be null or left out on a paged list. Every customer-facing email send (campaigns, sequences, one-off, automation, transactional and booking mail) refuses a listed address. 403 for a non-admin key is surfaced verbatim.", {
25
25
  page: z.number().int().min(1).optional().describe("Page number (default 1)"),
26
26
  perPage: z.number().int().min(1).max(100).optional().describe("Rows per page, 1-100 (default 25)"),
27
27
  }, async ({ page, perPage }) => {
@@ -1,5 +1,11 @@
1
1
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
2
  import { ConduytClient } from "../client.js";
3
+ /** (reportmath66, app lib/report-pivot.ts PIVOT_PERCENT_OF) a pivot measure shown as a share of its row / column / grand total */
4
+ export declare const PIVOT_PERCENT_OF: readonly ["row", "column", "total"];
5
+ /** (reportmath66, app lib/report-export-sheet.ts) the export's sheet: rows (the default) or pivot (the report's pivot as CSV) */
6
+ export declare const EXPORT_SHEETS: readonly ["rows", "pivot"];
7
+ /** the API's own sentence for sheet=pivot with format=xlsx (400 query_param_conflict); refused here before any request */
8
+ export declare const PIVOT_XLSX_CONFLICT = "sheet=pivot is a CSV export; the Excel workbook (format xlsx) already carries the Pivot sheet beside the rows";
3
9
  /**
4
10
  * (parity46, app branch reportbuilder45, lib/report-column-labels.ts) a saved report's own column headers: { <column name>: <header> }.
5
11
  * The API trims a header, then refuses one over 60 characters or holding a control character (line breaks, tabs, 0x00-0x1F, 0x7F-0x9F);
@@ -11,9 +11,15 @@ import { formatResult } from "../client.js";
11
11
  */
12
12
  const filterSchema = z.object({
13
13
  field: z.string().describe("A field name from conduyt_report_fields (base column, rollup, or cf:<key>)"),
14
- operator: z.string().describe("eq, neq, contains, gt, gte, lt, lte, between, in, isNull, isNotNull, or a relative-date operator (within_last_n, today, since_monday, this_calendar_month, previous_month, in_past, in_future…)"),
14
+ operator: z.string().describe("eq, neq, contains, gt, gte, lt, lte, between, in, isNull, isNotNull, or a relative-date operator (within_last_n, today, since_monday, this_calendar_week, previous_calendar_week (reportmath66: Monday 00:00 to Sunday 23:59:59.999 in the workspace time zone, no value; on a date custom field the seven calendar days), this_calendar_month, previous_month, in_past, in_future…)"),
15
15
  value: z.unknown().optional().describe("The value; [from, to] for between; a list for in; {n, unit} for within_last_n / within_next_n"),
16
16
  });
17
+ /** (reportmath66, app lib/report-pivot.ts PIVOT_PERCENT_OF) a pivot measure shown as a share of its row / column / grand total */
18
+ export const PIVOT_PERCENT_OF = ["row", "column", "total"];
19
+ /** (reportmath66, app lib/report-export-sheet.ts) the export's sheet: rows (the default) or pivot (the report's pivot as CSV) */
20
+ export const EXPORT_SHEETS = ["rows", "pivot"];
21
+ /** the API's own sentence for sheet=pivot with format=xlsx (400 query_param_conflict); refused here before any request */
22
+ export const PIVOT_XLSX_CONFLICT = "sheet=pivot is a CSV export; the Excel workbook (format xlsx) already carries the Pivot sheet beside the rows";
17
23
  const pivotSchema = z.object({
18
24
  rows: z.array(z.string()).min(1).max(2).describe("One or two groupable fields down the side"),
19
25
  columns: z.string().nullable().optional().describe("A groupable field across the top (omit for a single Total column)"),
@@ -21,6 +27,7 @@ const pivotSchema = z.object({
21
27
  aggregate: z.enum(["count", "sum", "avg", "min", "max"]),
22
28
  field: z.string().nullable().optional().describe("A numeric field (rollup or cf:<key>); omit for count"),
23
29
  format: z.enum(["number", "integer", "currency", "percent"]).optional().describe("How this measure is displayed (a property of the measure, not the report)"),
30
+ percentOf: z.enum(PIVOT_PERCENT_OF).nullable().optional().describe("(reportmath66) Show the measure as a share of its row total, its column total or the grand total: count and sum only (an average / min / max is refused), and row needs a column field (the API validates both: 422). The run keeps the raw value in each cell's values and adds shares (percent, one decimal; null for no value or a zero denominator), grandTotalShares and, with two row fields, the group subtotals' totalShares / shares. The same aggregate shown raw and as a share is two measures. Omitted or null = the value itself"),
24
31
  })).min(1).max(5),
25
32
  }).describe("Pivot table on the report (contacts / deals): every cell, row totals, column totals and the grand total come from the same filtered rows as the table; XLSX exports and deliveries add a Pivot sheet");
26
33
  /**
@@ -135,7 +142,7 @@ export function registerReportTools(server, client) {
135
142
  });
136
143
  return formatResult(result);
137
144
  });
138
- server.tool("conduyt_run_report", "Run a saved custom report: a page of rows (per_page ≤ 500), the total, the metric, the chart data (groupBy) and, on contacts/deals with groupBy2, the two-dimensional grouped rows.", {
145
+ server.tool("conduyt_run_report", "Run a saved custom report: a page of rows (per_page ≤ 500), the total, the metric, the chart data (groupBy) and, on contacts/deals with groupBy2, the two-dimensional grouped rows. (reportmath66) A pivot measure with percentOf keeps the raw aggregate in each cell's values and adds shares (same order as the measures; percent, one decimal; null for a measure shown as itself, no value or a zero / empty denominator), grandTotalShares and, with two row fields, the group subtotals' totalShares / shares; denominators: % of row = the cell's row total, % of column = the column total, % of total = the grand total. A pivot without percentOf answers exactly as before.", {
139
146
  id: z.string().uuid().describe("Saved report id (from conduyt_list_reports)"),
140
147
  page: z.number().int().min(1).optional(),
141
148
  per_page: z.number().int().min(1).max(500).optional(),
@@ -229,11 +236,14 @@ export function registerReportTools(server, client) {
229
236
  });
230
237
  return formatResult(result);
231
238
  });
232
- server.tool("conduyt_export_report", "Export every matching row of a saved report (up to 50,000) as CSV or XLSX text. Returns the file body; for a large report narrow the filters or ask for the scheduled delivery.", {
239
+ server.tool("conduyt_export_report", "Export every matching row of a saved report (up to 50,000) as CSV or XLSX text. Returns the file body; for a large report narrow the filters or ask for the scheduled delivery. (reportmath66) sheet: rows (the default) or pivot: the report's pivot as CSV (the Excel Pivot sheet's layout; a share measure's raw column is followed by a \"<column> · <measure> · % of row total / % of column total / % of grand total\" column, empty for no value or a zero denominator). sheet pivot with format xlsx is refused before any request (the API: 400 query_param_conflict, \"" + PIVOT_XLSX_CONFLICT + "\"; the workbook already carries the Pivot sheet); on a report without a pivot the API answers 400 report_has_no_pivot.", {
233
240
  id: z.string().uuid(),
234
241
  format: z.enum(["csv", "xlsx"]).optional().describe("csv (default) or xlsx"),
235
- }, async ({ id, format }) => {
236
- const result = await client.postText(`/api/v1/reports/custom/${encodeURIComponent(id)}/export?format=${format ?? "csv"}`, {});
242
+ sheet: z.enum(EXPORT_SHEETS).optional().describe("rows (default: the report's rows) or pivot (the report's pivot as CSV; csv only)"),
243
+ }, async ({ id, format, sheet }) => {
244
+ if (sheet === "pivot" && format === "xlsx")
245
+ return { content: [{ type: "text", text: JSON.stringify({ ok: false, error: PIVOT_XLSX_CONFLICT, sent: false }, null, 2) }], isError: true };
246
+ const result = await client.postText(`/api/v1/reports/custom/${encodeURIComponent(id)}/export?format=${format ?? "csv"}${sheet !== undefined ? `&sheet=${sheet}` : ""}`, {});
237
247
  return formatResult(result);
238
248
  });
239
249
  // ── Reporting P2 (2026-09-10): scheduled delivery of saved reports ────────────────────────────────────────────────
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Pinned copy of the app's single source of webhook events (lib/webhook-events.ts WEBHOOK_EVENTS and RESERVED_WEBHOOK_EVENTS at
3
+ * 33d412aca9, apigaps65 rule 3). apigaps65.parity.test.ts fails when `events` differs from the contracts snapshot's webhookEvents
4
+ * (the app catalog) or, with CONDUYT_APP_DIR, from the app file. Refresh both with the contracts.
5
+ */
6
+ export declare const WEBHOOK_EVENT_PIN: {
7
+ events: string[];
8
+ reserved: string[];
9
+ };
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Pinned copy of the app's single source of webhook events (lib/webhook-events.ts WEBHOOK_EVENTS and RESERVED_WEBHOOK_EVENTS at
3
+ * 33d412aca9, apigaps65 rule 3). apigaps65.parity.test.ts fails when `events` differs from the contracts snapshot's webhookEvents
4
+ * (the app catalog) or, with CONDUYT_APP_DIR, from the app file. Refresh both with the contracts.
5
+ */
6
+ export const WEBHOOK_EVENT_PIN = {
7
+ events: ["contact.created", "contact.updated", "contact.deleted", "contact.assigned", "lead.up_for_grabs", "contact.tagged", "contact.tag_added", "contact.tag_removed", "contact.sms_number_opt_out", "contact.sms_number_opt_in", "deal.created", "deal.updated", "deal.stage_changed", "deal.won", "deal.lost", "deal.deleted", "deal.stalled", "company.created", "company.updated", "company.deleted", "company.stage_changed", "company.tagged", "company.tag_removed", "message.sent", "message.received", "appointment.booked", "appointment.created", "appointment.updated", "appointment.cancelled", "task.created", "task.completed", "task.deleted", "form.submitted", "invoice.created", "invoice.sent", "invoice.viewed", "invoice.partly_paid", "invoice.paid", "invoice.overdue", "invoice.voided", "campaign.completed", "call.initiated", "call.completed", "call.reconciled", "call.dispositioned", "call.recording_ready", "call.transcribed", "call.missed", "call.voicemail_dropped", "call.voicemail_received", "document.generated", "document.sent", "document.viewed", "document.downloaded", "note.created", "sms.intent_classified", "playbook.enrolled", "playbook.step_completed", "playbook.completed", "chat.message.created", "chat.mention"],
8
+ reserved: ["campaign.completed", "document.viewed", "document.downloaded"],
9
+ };
@@ -1,3 +1,4 @@
1
1
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
2
  import { ConduytClient } from "../client.js";
3
+ export declare const WEBHOOK_EVENTS_DOC: string;
3
4
  export declare function registerWebhookTools(server: McpServer, client: ConduytClient): void;
@@ -1,6 +1,17 @@
1
1
  import { EVENT_USERS_DOC } from "./user-fields-doc.js";
2
2
  import { z } from "zod";
3
3
  import { formatResult } from "../client.js";
4
+ import { WEBHOOK_EVENT_PIN as webhookEventPin } from "./webhook-events.pin.js";
5
+ /**
6
+ * (apigaps65 rule 3) every subscribable event, from the pinned copy of the app's single source (lib/webhook-events.ts;
7
+ * the pin is tested against the contracts snapshot's webhookEvents and, with CONDUYT_APP_DIR, against the app file).
8
+ * The reserved ones are subscribable but no code path delivers them yet.
9
+ */
10
+ const RESERVED_EVENTS = webhookEventPin.reserved;
11
+ const DELIVERED_EVENTS = webhookEventPin.events.filter((e) => !RESERVED_EVENTS.includes(e));
12
+ export const WEBHOOK_EVENTS_DOC = `Subscribable events (${webhookEventPin.events.length}): ${DELIVERED_EVENTS.join(", ")}. ` +
13
+ `Reserved (subscribable, accepted by create / update, but never delivered yet): ${RESERVED_EVENTS.join(", ")}. ` +
14
+ "An event outside this list is refused with 400.";
4
15
  export function registerWebhookTools(server, client) {
5
16
  server.tool("conduyt_list_webhooks", "List all registered webhooks with their events, status, and failure counts.", {
6
17
  page: z.number().optional().describe("Page number (default 1)"),
@@ -14,7 +25,7 @@ export function registerWebhookTools(server, client) {
14
25
  const result = await client.get(`/api/v1/webhooks/manage?${params}`);
15
26
  return formatResult(result);
16
27
  });
17
- server.tool("conduyt_create_webhook", "Register a new webhook endpoint. Returns the signing secret once — store it securely. Events: contact.created/updated/deleted, contact.tag_added/removed, deal.created/updated/stage_changed/won/lost/deleted, company.created/updated/deleted, message.sent/received, appointment.created/updated/cancelled, campaign.completed." + EVENT_USERS_DOC, {
28
+ server.tool("conduyt_create_webhook", "Register a new webhook endpoint. Returns the signing secret once — store it securely. " + WEBHOOK_EVENTS_DOC + EVENT_USERS_DOC, {
18
29
  url: z.string().describe("Webhook endpoint URL (HTTPS required in production)"),
19
30
  events: z.array(z.string()).describe("Events to subscribe to (e.g. ['contact.created', 'deal.won'])"),
20
31
  description: z.string().optional().describe("Human-readable description of this webhook"),
@@ -23,7 +34,7 @@ export function registerWebhookTools(server, client) {
23
34
  const result = await client.post("/api/v1/webhooks/manage", params);
24
35
  return formatResult(result);
25
36
  });
26
- server.tool("conduyt_update_webhook", "Update a webhook — change URL, events, or enable/disable. Reactivating resets the failure count." + EVENT_USERS_DOC, {
37
+ server.tool("conduyt_update_webhook", "Update a webhook — change URL, events, or enable/disable. Reactivating resets the failure count. " + WEBHOOK_EVENTS_DOC + EVENT_USERS_DOC, {
27
38
  id: z.string().describe("Webhook UUID"),
28
39
  url: z.string().optional().describe("Updated endpoint URL"),
29
40
  events: z.array(z.string()).optional().describe("Updated event subscriptions"),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "conduyt-mcp",
3
- "version": "4.105.43",
3
+ "version": "4.108.0",
4
4
  "mcpName": "com.conduyt/mcp",
5
5
  "description": "MCP server for Conduyt CRM — expose CRM operations as AI-accessible tools",
6
6
  "type": "module",
@@ -45,6 +45,11 @@
45
45
  "status": "excluded",
46
46
  "reason": "CRON_SECRET-gated infrastructure jobs; never key-callable"
47
47
  },
48
+ {
49
+ "match": "POST /api/v1/document-reads/engine-callback",
50
+ "status": "excluded",
51
+ "reason": "(parity66a, app ocr66) the reading engine's signed event callback: no session and no API key, the caller is the engine (Bearer shared secret + HMAC X-Conduyt-Signature over the raw body); never key-callable"
52
+ },
48
53
  {
49
54
  "match": "POST /api/v1/account-exports",
50
55
  "status": "planned",
@@ -1,10 +1,10 @@
1
1
  {
2
- "generatedAt": "2026-11-24T21:38:03.704Z",
3
- "toolCount": 453,
4
- "totalEndpoints": 1230,
2
+ "generatedAt": "2026-11-26T12:42:25.096Z",
3
+ "toolCount": 463,
4
+ "totalEndpoints": 1239,
5
5
  "counts": {
6
- "covered": 403,
7
- "excluded": 376,
6
+ "covered": 410,
7
+ "excluded": 378,
8
8
  "planned": 451,
9
9
  "uncategorized": 0
10
10
  },
@@ -1872,6 +1872,12 @@
1872
1872
  "status": "planned",
1873
1873
  "reason": "contact subroutes beyond the core CRUD/search tools"
1874
1874
  },
1875
+ "GET /api/v1/contacts/:id/document-reads": {
1876
+ "status": "covered",
1877
+ "tools": [
1878
+ "conduyt_list_contact_document_reads"
1879
+ ]
1880
+ },
1875
1881
  "GET /api/v1/contacts/:id/duplicate-proposals": {
1876
1882
  "status": "covered",
1877
1883
  "tools": [
@@ -2120,6 +2126,10 @@
2120
2126
  "status": "excluded",
2121
2127
  "reason": "CRON_SECRET-gated infrastructure jobs; never key-callable"
2122
2128
  },
2129
+ "GET /api/v1/cron/document-reader-autoread": {
2130
+ "status": "excluded",
2131
+ "reason": "CRON_SECRET-gated infrastructure jobs; never key-callable"
2132
+ },
2123
2133
  "GET /api/v1/cron/dpp-nightly": {
2124
2134
  "status": "excluded",
2125
2135
  "reason": "CRON_SECRET-gated infrastructure jobs; never key-callable"
@@ -3146,6 +3156,34 @@
3146
3156
  "status": "planned",
3147
3157
  "reason": "DNC import beyond the typed DNC tools"
3148
3158
  },
3159
+ "POST /api/v1/document-reads": {
3160
+ "status": "covered",
3161
+ "tools": [
3162
+ "conduyt_start_document_read"
3163
+ ]
3164
+ },
3165
+ "GET /api/v1/document-reads/:id": {
3166
+ "status": "covered",
3167
+ "tools": [
3168
+ "conduyt_get_document_read"
3169
+ ]
3170
+ },
3171
+ "POST /api/v1/document-reads/:id/confirm": {
3172
+ "status": "covered",
3173
+ "tools": [
3174
+ "conduyt_confirm_document_read_values"
3175
+ ]
3176
+ },
3177
+ "POST /api/v1/document-reads/:id/fill": {
3178
+ "status": "covered",
3179
+ "tools": [
3180
+ "conduyt_fill_deal_from_document_read"
3181
+ ]
3182
+ },
3183
+ "POST /api/v1/document-reads/engine-callback": {
3184
+ "status": "excluded",
3185
+ "reason": "(parity66a, app ocr66) the reading engine's signed event callback: no session and no API key, the caller is the engine (Bearer shared secret + HMAC X-Conduyt-Signature over the raw body); never key-callable"
3186
+ },
3149
3187
  "GET /api/v1/document-templates": {
3150
3188
  "status": "planned",
3151
3189
  "reason": "document template management"
@@ -4754,6 +4792,9 @@
4754
4792
  "conduyt_set_contact_table_defaults",
4755
4793
  "conduyt_get_call_recording_settings",
4756
4794
  "conduyt_get_calling_hours",
4795
+ "conduyt_update_document_reader_enabled",
4796
+ "conduyt_get_document_reader_settings",
4797
+ "conduyt_update_document_reader_settings",
4757
4798
  "conduyt_get_lead_pool_settings",
4758
4799
  "conduyt_update_lead_pool_settings",
4759
4800
  "conduyt_get_lifecycle_settings",
@@ -4764,7 +4805,9 @@
4764
4805
  "PATCH /api/v1/settings": {
4765
4806
  "status": "covered",
4766
4807
  "tools": [
4767
- "conduyt_set_contact_table_defaults"
4808
+ "conduyt_set_contact_table_defaults",
4809
+ "conduyt_update_document_reader_enabled",
4810
+ "conduyt_update_document_reader_settings"
4768
4811
  ]
4769
4812
  },
4770
4813
  "GET /api/v1/settings/ai": {
@@ -4832,6 +4875,18 @@
4832
4875
  "status": "planned",
4833
4876
  "reason": "account settings read/update surfaces"
4834
4877
  },
4878
+ "GET /api/v1/settings/document-reader-types": {
4879
+ "status": "covered",
4880
+ "tools": [
4881
+ "conduyt_get_document_reader_types"
4882
+ ]
4883
+ },
4884
+ "PUT /api/v1/settings/document-reader-types": {
4885
+ "status": "covered",
4886
+ "tools": [
4887
+ "conduyt_put_document_reader_types"
4888
+ ]
4889
+ },
4835
4890
  "GET /api/v1/settings/dormancy": {
4836
4891
  "status": "planned",
4837
4892
  "reason": "account settings read/update surfaces"