iit-mcp-autotask 0.65.0 → 0.65.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -215,6 +215,12 @@ What the write access can and cannot do (full reference: [docs/write-gate.md](do
215
215
  - The company scope is read from the live records the write touches (the target, its parent, the
216
216
  ticket, project, task or contract it references, and any `companyID` it sets), never from names
217
217
  or titles. A reference that cannot be read is refused.
218
+ - Documents use the generic tools. Read published roots with `autotask_query` or
219
+ `autotask_read`, including `documents.listByParent` and `documents.getByParent` by category.
220
+ A company run scope restricts these reads to the document owner. Creation and changes to
221
+ `companyID` or `publish` require account-wide scope because ownership and audience are
222
+ separate. Metadata PATCH and confirmed DELETE bind the scoped document's owner and revision.
223
+ Drafts are hidden by Autotask and can prevent a write after a successful preview.
218
224
 
219
225
  Every string in a write payload is NFC-normalised after the unsafe-character strip and before the
220
226
  plan hash and the send (issue 59): the vendor stores a precomposed `é` (U+00E9) unchanged, but a
package/capabilities.json CHANGED
@@ -74,7 +74,7 @@
74
74
  },
75
75
  {
76
76
  "id": "autotask.platform.catalog",
77
- "description": "Find the exact operation key for anything without a dedicated tool: ranked search (q) over the 1,444 registry operations, with effect and whether this deployment serves it. No vendor call.",
77
+ "description": "Find the exact operation key for anything without a dedicated tool: ranked search (q) over the 1,455 registry operations, with effect and whether this deployment serves it. No vendor call.",
78
78
  "mcpPrimitive": "tool",
79
79
  "toolName": "autotask_catalog",
80
80
  "type": "read",
@@ -480,7 +480,7 @@
480
480
  "autotask_describe",
481
481
  "autotask_read"
482
482
  ],
483
- "backingRegistryOperations": 1444,
483
+ "backingRegistryOperations": 1455,
484
484
  "note": "autotask_catalog finds the exact operation key (ranked search), autotask_describe serves its contract, autotask_read runs any effect=read key. Writes go through the operator profile (autotask_write then autotask_apply); authenticate.* is never served."
485
485
  },
486
486
  "schemas": {}
package/dist/policy.d.ts CHANGED
@@ -35,6 +35,7 @@ export declare const CREDENTIAL_RESOURCES: readonly ["authenticate"];
35
35
  export declare function isSecretOperation(operation: string): boolean;
36
36
  export declare function isStaffAttachmentWrite(operation: string): boolean;
37
37
  export declare function staffAttachmentScopeReason(operation: string, runScope: RunScope | undefined): Reason | undefined;
38
+ export declare function documentUpdateScopeReason(operation: string, data: unknown, scope: RunScope | undefined): Reason | undefined;
38
39
  /** Resolve the account scope shared by discovery and the write evaluator. */
39
40
  export declare function accountWriteScopeReason(operation: string, accountWide: boolean, runScope: RunScope | undefined): Reason | undefined;
40
41
  /**
package/dist/policy.js CHANGED
@@ -44,8 +44,17 @@ export function staffAttachmentScopeReason(operation, runScope) {
44
44
  detail: `${operation} requires a run scope of {"all":true} because the parent does not establish company ownership`,
45
45
  };
46
46
  }
47
+ export function documentUpdateScopeReason(operation, data, scope) {
48
+ if (operation !== 'documents.update' || scope === undefined || !('companyIds' in scope)
49
+ || data === null || typeof data !== 'object' || !Object.keys(data).some(field => /^(publish|companyid)$/i.test(field)))
50
+ return undefined;
51
+ return { code: 'TARGET_NOT_IN_SCOPE', detail: 'Updating document ownership or publication audience requires account-wide run scope.' };
52
+ }
47
53
  /** Resolve the account scope shared by discovery and the write evaluator. */
48
54
  export function accountWriteScopeReason(operation, accountWide, runScope) {
55
+ if (operation === 'documents.create' && (runScope === undefined || 'companyIds' in runScope)) {
56
+ return { code: 'TARGET_NOT_IN_SCOPE', detail: 'documents.create requires account-wide run scope because document ownership does not establish the publication audience.' };
57
+ }
49
58
  const staffAttachment = staffAttachmentScopeReason(operation, runScope);
50
59
  if (staffAttachment !== undefined)
51
60
  return staffAttachment;
@@ -17,6 +17,7 @@ import { abortedAnswer } from './dispatch.js';
17
17
  import { markResult } from './results/untrusted.js';
18
18
  import { ok } from './results/envelope.js';
19
19
  import { assertOperationPermitted } from '../policy.js';
20
+ import { documentReadArgs } from './documents.js';
20
21
  import { scopedCatalogCall } from './field-pointer.js';
21
22
  /** The server line for an SDK aggregate answer: numbers only, and the partial marker whenever the SDK flags truncation. */
22
23
  function summaryLine(operation, result) {
@@ -51,7 +52,9 @@ export async function runAggregate(ctx, operation, rawFilter, opts, signal, extr
51
52
  for (const key of ['groupBy', 'sum', 'top', 'limit', 'names'])
52
53
  if (opts[key] !== undefined)
53
54
  bag[key] = opts[key];
54
- const answer = await ctx.ops.invokeRead(ctx.client, helper, Object.keys(bag).length > 0 ? [operation, filter, bag] : [operation, filter], undefined, signal).catch((err) => {
55
+ const args = Object.keys(bag).length > 0 ? [operation, filter, bag] : [operation, filter];
56
+ documentReadArgs(ctx, helper, args, args);
57
+ const answer = await ctx.ops.invokeRead(ctx.client, helper, args, undefined, signal).catch((err) => {
55
58
  // node-autotask #280: a bad filter / groupBy / sum name is a zero-wire CONFIG_ERROR; point at the scoped field catalog
56
59
  if (!(err instanceof AutotaskConfigError) || !err.message.includes('is not a field of'))
57
60
  throw err;
@@ -77,7 +77,7 @@ export declare function isEntityReadPermissionRefusal(error: {
77
77
  httpStatus?: unknown;
78
78
  category?: unknown;
79
79
  }): boolean;
80
- export declare function isDocumentCategoryReadOperation(operation: unknown): boolean;
80
+ export declare function isDocumentReadOperation(operation: unknown): boolean;
81
81
  /** The served tool for this row's operation in a deployment serving `served`, or `null`. */
82
82
  export declare function servedToolName(row: CatalogRow, served: ReadonlySet<string>): string | null;
83
83
  /** The registry keys projected onto an MCP tool name (the reverse of {@link TOOL_NAME_BY_OP}); empty when none. */
@@ -122,7 +122,7 @@ export declare function sdkCacheOptions(cache: 'on' | 'off'): Pick<AutotaskConfi
122
122
  * fails the boot (or the CI test) instead of quietly shipping a tool surface that no longer
123
123
  * describes the SDK behind it.
124
124
  */
125
- export declare const BUILT_AGAINST_PLAN_HASH = "86416d6a76ecf010aa7956b6910b253de22ddabec45711f79dd4aeaa38c0466e";
125
+ export declare const BUILT_AGAINST_PLAN_HASH = "851551c93be98a8eb27a8acf3d7c0e895e3024097150a86f5f9eed6229b1bd32";
126
126
  /**
127
127
  * Fail fast when the installed SDK's plan has moved out from under this surface.
128
128
  * Called at boot (main.ts) and safe to call repeatedly (pure comparison).
@@ -124,11 +124,11 @@ export function isRegisteredMetadataRead(operation) {
124
124
  /** A direct HTTP 403 on these reads can be an entity permission refusal. */
125
125
  export function isEntityReadPermissionRefusal(error) {
126
126
  return error.httpStatus === 403 && error.category === 'auth'
127
- && (isStaffReadOperation(error.operation) || isDocumentCategoryReadOperation(error.operation));
127
+ && (isStaffReadOperation(error.operation) || isDocumentReadOperation(error.operation));
128
128
  }
129
- export function isDocumentCategoryReadOperation(operation) {
129
+ export function isDocumentReadOperation(operation) {
130
130
  const record = typeof operation === 'string' ? recordById(operation) : undefined;
131
- return record?.effect === 'read' && record.resource === 'document_categories';
131
+ return record?.effect === 'read' && (record.resource === 'document_categories' || record.resource === 'documents');
132
132
  }
133
133
  /** The served tool for this row's operation in a deployment serving `served`, or `null`. */
134
134
  export function servedToolName(row, served) {
@@ -227,7 +227,7 @@ export function sdkCacheOptions(cache) {
227
227
  * fails the boot (or the CI test) instead of quietly shipping a tool surface that no longer
228
228
  * describes the SDK behind it.
229
229
  */
230
- export const BUILT_AGAINST_PLAN_HASH = '86416d6a76ecf010aa7956b6910b253de22ddabec45711f79dd4aeaa38c0466e';
230
+ export const BUILT_AGAINST_PLAN_HASH = '851551c93be98a8eb27a8acf3d7c0e895e3024097150a86f5f9eed6229b1bd32';
231
231
  /**
232
232
  * Fail fast when the installed SDK's plan has moved out from under this surface.
233
233
  * Called at boot (main.ts) and safe to call repeatedly (pure comparison).
@@ -4,7 +4,7 @@ import { AutotaskClient, errorFromStatus } from 'node-autotask';
4
4
  import { invokeDelete, invokeRead, invokeReadPages, invokeWrite, relationshipMap, resolveAny, searchAcrossResources } from 'node-autotask/operations';
5
5
  import { serverCredentialDefaults } from '../../config/load.js';
6
6
  import { normalizeBaseUrl } from '../../base-hosts.js';
7
- import { isDocumentCategoryReadOperation, isRegisteredMetadataRead, sdkCacheOptions } from '../catalog-data.js';
7
+ import { isDocumentReadOperation, isRegisteredMetadataRead, sdkCacheOptions } from '../catalog-data.js';
8
8
  import { captureReadRuntime } from '../read-runtime.js';
9
9
  // ---------------------------------------------------------------------------
10
10
  // SDK client construction
@@ -23,7 +23,7 @@ const READ_AUDIT_CODES = new Set([
23
23
  function auditErrorCode(code, operation, status) {
24
24
  if (typeof code !== 'string')
25
25
  return undefined;
26
- if (isRegisteredMetadataRead(operation) || isDocumentCategoryReadOperation(operation)) {
26
+ if (isRegisteredMetadataRead(operation) || isDocumentReadOperation(operation)) {
27
27
  // A terminal SDK failure can carry the status from an earlier retry.
28
28
  if (READ_AUDIT_CODES.has(code))
29
29
  return code;
@@ -2,19 +2,22 @@
2
2
  import { AsyncLocalStorage } from 'node:async_hooks';
3
3
  import { AutotaskClient, isAutotaskError } from 'node-autotask';
4
4
  import { isAuthFailure } from '../results/errors.js';
5
- import { isDocumentCategoryReadOperation, isRegisteredMetadataRead, isStaffReadOperation, recordById, toolDescription, untrustedFieldsOf } from '../catalog-data.js';
5
+ import { isDocumentReadOperation, isRegisteredMetadataRead, isStaffReadOperation, recordById, toolDescription, untrustedFieldsOf } from '../catalog-data.js';
6
6
  // A real client with this hook handles eviction once per wire refusal, even if multiple readers share the result.
7
7
  const auditInvalidatesCredentialReads = new WeakSet();
8
8
  const impersonationValidation = new AsyncLocalStorage();
9
9
  const invalidatedValidationErrors = new WeakSet();
10
10
  function isCredentialReadDenial(operation, status, impersonated) {
11
11
  return (status === 401 || (status === 403 && impersonated)) &&
12
- (isStaffReadOperation(operation) || isRegisteredMetadataRead(operation) || isDocumentCategoryReadOperation(operation));
12
+ (isStaffReadOperation(operation) || isRegisteredMetadataRead(operation) || isDocumentReadOperation(operation));
13
13
  }
14
- function isCategoryMutation(operation, method) {
14
+ function isGuardedDocumentMutation(operation, method) {
15
15
  return (operation === 'document_categories.create' && method === 'POST')
16
16
  || (operation === 'document_categories.update' && method === 'PUT')
17
- || (operation === 'document_categories.delete' && method === 'DELETE');
17
+ || (operation === 'document_categories.delete' && method === 'DELETE')
18
+ || (operation === 'documents.create' && method === 'POST')
19
+ || (operation === 'documents.update' && method === 'PATCH')
20
+ || (operation === 'documents.delete' && method === 'DELETE');
18
21
  }
19
22
  function invalidateCredentialReads(pool, config, client, log) {
20
23
  // A pinned stdio or in-flight client can outlive its pool entry. Clear its stores if the pool did not.
@@ -68,7 +71,7 @@ export function getPooledClient(pool, config, log) {
68
71
  const validationDenial = validation?.client === client && config.impersonationResourceId !== undefined
69
72
  && operation === 'resources.get' && method === 'GET' && (status === 401 || status === 403);
70
73
  // The wire can settle after apply has returned an unknown outcome.
71
- if (readDenial || validationDenial || (status === 401 && isCategoryMutation(operation, method))) {
74
+ if (readDenial || validationDenial || (status === 401 && isGuardedDocumentMutation(operation, method))) {
72
75
  invalidateCredentialReads(pool, config, client, log);
73
76
  }
74
77
  if (validationDenial) {
@@ -108,6 +108,8 @@ export interface ToolDeps {
108
108
  * principal (the token's, or `AUTOTASK_PRINCIPAL` on stdio) and its run scope. Absent on readonly.
109
109
  */
110
110
  write?: WriteDeps;
111
+ /** Effective token scope, when present on a read-only request. */
112
+ runScope?: RunScope;
111
113
  /** The client capabilities the connection's `initialize` declared (2025-era only; absent on a stateless request). */
112
114
  clientCapabilities?: () => ClientCapabilities | undefined;
113
115
  }
@@ -21,6 +21,7 @@ import { abortedResult, closedArgsError, errorContent, isShapeOnlyVendorOperatio
21
21
  import { isFileOperation, markFilePayload, markReadResult, markResult, markServerField } from './results/untrusted.js';
22
22
  import { mirrorEnvelope } from './results/envelope.js';
23
23
  import { assertOperationPermitted } from '../policy.js';
24
+ import { documentCompanyScope, documentReadArgs, projectDocumentRows, verifyDocumentRows } from './documents.js';
24
25
  import { scopeRequiredInput } from './scope-guard.js';
25
26
  import { fieldNameInput } from './field-pointer.js';
26
27
  /** The MCP request's AbortSignal, when the transport provides one (architecture 7.6). */
@@ -272,6 +273,8 @@ export async function readOneItem(ctx, operation, args, signal, opts, projectRaw
272
273
  cleanArgs[0] = bag;
273
274
  }
274
275
  }
276
+ const includeFields = cleanArgs[0]?.includeFields;
277
+ documentReadArgs(ctx, operation, cleanArgs, args);
275
278
  let scopeNote;
276
279
  if (operation.endsWith('.query') && cleanArgs[0] !== null && typeof cleanArgs[0] === 'object' && !Array.isArray(cleanArgs[0])) {
277
280
  const bag = cleanArgs[0];
@@ -286,7 +289,9 @@ export async function readOneItem(ctx, operation, args, signal, opts, projectRaw
286
289
  const bag = (cleanArgs[0] ?? {});
287
290
  cleanArgs[0] = { ...(Array.isArray(bag.fields) && bag.fields.length > 0 ? { labels: true } : {}), maxBytes: FIELD_CATALOG_MAX_BYTES, ...bag };
288
291
  }
289
- const result = await ctx.ops.invokeRead(ctx.client, operation, cleanArgs, opts, signal).catch((err) => {
292
+ const companies = documentCompanyScope(ctx);
293
+ const invokeOpts = operation === 'documents.get' && companies !== undefined ? { ...opts, fresh: true } : opts;
294
+ let result = await ctx.ops.invokeRead(ctx.client, operation, cleanArgs, invokeOpts, signal).catch((err) => {
290
295
  // #224: a refused cursor the caller passed is the caller's input; a refused vendor continuation is not
291
296
  if (CURSOR_OPS.has(operation) && err?.code === 'RESPONSE_REJECTED' && cleanArgs.some((a) => a !== null && typeof a === 'object' && typeof a.cursor === 'string')) {
292
297
  Object.assign(err, { callerInput: true });
@@ -304,6 +309,15 @@ export async function readOneItem(ctx, operation, args, signal, opts, projectRaw
304
309
  throw errorFromStatus(authFailure.httpStatus, undefined, undefined, authFailure.operation);
305
310
  }
306
311
  }
312
+ if (companies !== undefined && (operation === 'documents.get' || operation === 'documents.getByParent')) {
313
+ verifyDocumentRows(operation, [result], companies);
314
+ }
315
+ if (companies !== undefined && (operation === 'documents.query' || operation === 'documents.listByParent')) {
316
+ const page = result;
317
+ verifyDocumentRows(operation, page.items, companies);
318
+ if (operation === 'documents.query')
319
+ result = { ...page, items: projectDocumentRows(page.items, includeFields) };
320
+ }
307
321
  // Raw evidence must precede deepMarkUntrusted, which replaces excessively nested values.
308
322
  if (projectRaw !== undefined)
309
323
  return { result: projectRaw(result), ...(scopeNote !== undefined ? { scopeNote } : {}) };
@@ -0,0 +1,11 @@
1
+ import type { ToolContext } from './context/types.js';
2
+ /** Keep safe IDs in their numeric form so equivalent inputs use the same approval key. */
3
+ export declare function documentId(value: unknown): number | string | undefined;
4
+ export declare function documentCategoryId(value: unknown): number | undefined;
5
+ export declare function isDocumentOwner(value: unknown): value is number;
6
+ export declare function documentCompanyScope(ctx: ToolContext): readonly number[] | undefined;
7
+ export declare function scopedDocumentQuery(operation: string, bag: Record<string, unknown>, companies: readonly number[] | undefined): Record<string, unknown>;
8
+ export declare function documentReadArgs(ctx: ToolContext, operation: string, args: unknown[], raw: readonly unknown[]): void;
9
+ /** If a vendor page contradicts its scope, refuse the entire page rather than returning misleading totals or links. */
10
+ export declare function verifyDocumentRows(operation: string, rows: readonly unknown[], companies: readonly number[] | undefined): void;
11
+ export declare function projectDocumentRows(rows: readonly unknown[], includeFields: unknown): readonly unknown[];
@@ -0,0 +1,133 @@
1
+ import { PolicyDeniedError } from '../policy.js';
2
+ import { InputInvalidError } from './dispatch.js';
3
+ import { assertFilterShape } from './schemas.js';
4
+ const maxCategory = 2_147_483_647;
5
+ const maxDocument = '9223372036854775807';
6
+ const documentFilterLimit = 8_000;
7
+ /** Keep safe IDs in their numeric form so equivalent inputs use the same approval key. */
8
+ export function documentId(value) {
9
+ if (typeof value === 'number')
10
+ return Number.isSafeInteger(value) && value > 0 ? value : undefined;
11
+ if (typeof value !== 'string' || !/^[1-9]\d{0,18}$/.test(value) || value !== value.trim()
12
+ || (value.length === maxDocument.length && value > maxDocument))
13
+ return undefined;
14
+ const numeric = Number(value);
15
+ return Number.isSafeInteger(numeric) ? numeric : value;
16
+ }
17
+ export function documentCategoryId(value) {
18
+ const id = documentId(value);
19
+ return typeof id === 'number' && id <= maxCategory ? id : undefined;
20
+ }
21
+ export function isDocumentOwner(value) {
22
+ return typeof value === 'number' && Number.isInteger(value) && value >= 0 && value <= maxCategory;
23
+ }
24
+ export function documentCompanyScope(ctx) {
25
+ const scope = ctx.write?.runScope ?? ctx.runScope;
26
+ return scope !== undefined && 'companyIds' in scope ? scope.companyIds.filter(isDocumentOwner) : undefined;
27
+ }
28
+ function scopeError(operation, message) {
29
+ throw new PolicyDeniedError(message, { operation });
30
+ }
31
+ function filterDocumentCompanies(operation, filter, companies) {
32
+ if (companies.length === 0)
33
+ scopeError(operation, 'The effective run scope contains no valid Documents owner company IDs.');
34
+ const conditions = Array.isArray(filter) ? filter : filter?.filter ?? [];
35
+ // Top-level query conditions are ANDed by the SDK. A caller's OR group stays nested.
36
+ const owner = { field: 'companyID', op: 'in', value: [...new Set(companies)] };
37
+ // The SDK validates the combined filter. Report when the authority predicate alone cannot fit.
38
+ if (JSON.stringify({ filter: [owner] }).length > documentFilterLimit) {
39
+ scopeError(operation, 'The configured Documents company scope exceeds the vendor query filter limit. Use a smaller company run scope or a scoped item or category read.');
40
+ }
41
+ return [...conditions, owner];
42
+ }
43
+ function assertDocumentAggregate(ctx, operation, opts) {
44
+ if (operation !== 'documents.query' || documentCompanyScope(ctx) === undefined)
45
+ return;
46
+ const { groupBy, sum } = (opts ?? {});
47
+ if ((groupBy !== undefined && (!Array.isArray(groupBy) || groupBy.length > 0))
48
+ || (sum !== undefined && (!Array.isArray(sum) || sum.length > 0))) {
49
+ scopeError(operation, 'Grouped Document totals require account-wide scope. Use a count or query whose rows can be checked against the owner company.');
50
+ }
51
+ }
52
+ function requestsDocumentField(fields, name) {
53
+ return fields.some(field => typeof field === 'string' && field.replace(/^documents\./, '').toLowerCase() === name);
54
+ }
55
+ export function scopedDocumentQuery(operation, bag, companies) {
56
+ if (companies === undefined)
57
+ return bag;
58
+ const { includeFields } = bag;
59
+ return {
60
+ ...bag,
61
+ filter: filterDocumentCompanies(operation, bag.filter, companies),
62
+ ...(Array.isArray(includeFields) && !requestsDocumentField(includeFields, 'companyid')
63
+ ? { includeFields: [...includeFields, 'companyID'] } : {}),
64
+ };
65
+ }
66
+ function assertDocumentResolveResources(resources) {
67
+ if (resources === undefined)
68
+ return;
69
+ if (!Array.isArray(resources) || resources.some(resource => typeof resource !== 'string' || resource.trim() === '')) {
70
+ throw new InputInvalidError('resources must be an array of resource keys.', 'args.1.resources', 'operations.resolveAny');
71
+ }
72
+ if (resources.includes('documents')) {
73
+ scopeError('operations.resolveAny', 'Use documents.get or documents.getByParent with autotask_read. The resolver cannot verify Documents owner scope.');
74
+ }
75
+ }
76
+ export function documentReadArgs(ctx, operation, args, raw) {
77
+ if (operation === 'operations.resolveAny')
78
+ assertDocumentResolveResources(args[1]?.resources);
79
+ const companies = documentCompanyScope(ctx);
80
+ if (operation === 'operations.aggregate' && args[0] === 'documents.query' && companies !== undefined) {
81
+ assertDocumentAggregate(ctx, args[0], args[2]);
82
+ if (args[1] !== undefined)
83
+ assertFilterShape(args[1], operation);
84
+ args[1] = filterDocumentCompanies(args[0], args[1], companies);
85
+ return;
86
+ }
87
+ if (!operation.startsWith('documents.'))
88
+ return;
89
+ if (operation === 'documents.getByParent' || operation === 'documents.listByParent') {
90
+ const parent = documentCategoryId(raw[0]);
91
+ if (parent === undefined)
92
+ throw new InputInvalidError('parentId must be a positive signed 32-bit category ID.', 'args.0', operation);
93
+ args[0] = parent;
94
+ }
95
+ if (operation === 'documents.get' || operation === 'documents.getByParent') {
96
+ const i = operation === 'documents.get' ? 0 : 1;
97
+ const id = documentId(raw[i]);
98
+ if (id === undefined)
99
+ throw new InputInvalidError('id must be a positive signed 64-bit document ID. Use a canonical decimal string above Number.MAX_SAFE_INTEGER.', `args.${i}`, operation);
100
+ args[i] = id;
101
+ }
102
+ if ((operation === 'documents.query' || operation === 'documents.count') && companies !== undefined
103
+ && (args[0] === undefined || (args[0] !== null && typeof args[0] === 'object' && !Array.isArray(args[0])))) {
104
+ const bag = (args[0] ?? {});
105
+ assertFilterShape(bag.filter, operation);
106
+ args[0] = operation === 'documents.count' ? { ...bag, filter: filterDocumentCompanies(operation, bag.filter, companies) }
107
+ : scopedDocumentQuery(operation, bag, companies);
108
+ }
109
+ }
110
+ /** If a vendor page contradicts its scope, refuse the entire page rather than returning misleading totals or links. */
111
+ export function verifyDocumentRows(operation, rows, companies) {
112
+ if (companies === undefined)
113
+ return;
114
+ if (rows.some(row => !isDocumentOwner(row?.companyID))) {
115
+ scopeError(operation, 'Autotask did not establish the owner company for every returned document.');
116
+ }
117
+ if (rows.some(row => !companies.includes(row.companyID))) {
118
+ scopeError(operation, 'Autotask returned a document outside the effective owner company scope.');
119
+ }
120
+ }
121
+ export function projectDocumentRows(rows, includeFields) {
122
+ if (!Array.isArray(includeFields) || requestsDocumentField(includeFields, 'companyid'))
123
+ return rows;
124
+ const keepOwnerName = requestsDocumentField(includeFields, 'companyidname');
125
+ return rows.map(row => {
126
+ const projected = { ...row };
127
+ delete projected.companyID;
128
+ if (!keepOwnerName)
129
+ delete projected.companyIDName;
130
+ return projected;
131
+ });
132
+ }
133
+ //# sourceMappingURL=documents.js.map
@@ -12,6 +12,7 @@ import { AutotaskConfigError } from 'node-autotask';
12
12
  import { QUERY_INPUT, QUERY_LIMIT, assertFilterShape, closedInput } from './schemas.js';
13
13
  import { isDeletedActivityAuditResource, staffReadParentFilter } from './catalog-data.js';
14
14
  import { abortedAnswer, InputInvalidError } from './dispatch.js';
15
+ import { documentCompanyScope, projectDocumentRows, scopedDocumentQuery, verifyDocumentRows } from './documents.js';
15
16
  import { runAggregate } from './aggregate.js';
16
17
  import { markResult, markServerField, PROVENANCE, sanitiseVendorOutput } from './results/untrusted.js';
17
18
  import { bytesCappedNote, QUERY_MAX_BYTES, withinQueryBudget } from './query-budget.js';
@@ -103,10 +104,15 @@ export function buildQuery(ctx) {
103
104
  bag.noteChars = args.note_chars;
104
105
  if (args.acknowledge_unscoped !== undefined)
105
106
  bag.acknowledgeUnscoped = args.acknowledge_unscoped;
106
- const result = await ctx.ops.invokeRead(ctx.client, operation, [bag], undefined, signal)
107
+ const companies = args.resource === 'documents' ? documentCompanyScope(ctx) : undefined;
108
+ const rawResult = await ctx.ops.invokeRead(ctx.client, operation, [scopedDocumentQuery(operation, bag, companies)], undefined, signal)
107
109
  .catch((err) => { throw fieldNameInput(scopeRequiredInput(err, 'filter', true), true); });
108
- if (result === undefined)
110
+ if (rawResult === undefined)
109
111
  return abortedAnswer(ctx.correlationId);
112
+ const page = rawResult;
113
+ if (companies !== undefined)
114
+ verifyDocumentRows(operation, page.items, companies);
115
+ const result = companies === undefined ? rawResult : { ...page, items: projectDocumentRows(page.items, includeFields) };
110
116
  const v = result;
111
117
  const n = v.count ?? v.total ?? (Array.isArray(v.items) ? v.items.length : undefined);
112
118
  const capped = result.noteCharsTruncated;
@@ -217,15 +223,19 @@ async function outputPathAnswer(ctx, resource, operation, noun, fields, args, si
217
223
  relativePath: args.output_path,
218
224
  });
219
225
  const asTsv = args.format === 'tsv';
226
+ const companies = resource === 'documents' ? documentCompanyScope(ctx) : undefined;
220
227
  const exported = await exportQueryFile({
221
228
  target, fields, format: asTsv ? 'tsv' : 'json', signal,
222
- readPages: consume => ctx.ops.invokeReadPages(ctx.client, operation, [{
229
+ readPages: consume => ctx.ops.invokeReadPages(ctx.client, operation, [scopedDocumentQuery(operation, {
223
230
  filter: args.filter,
224
231
  limit: 500,
225
232
  walk: { maxRows: OUTPUT_MAX_ROWS },
226
233
  ...(args.include_fields === undefined ? {} : { includeFields: args.include_fields }),
227
234
  ...(args.acknowledge_unscoped === undefined ? {} : { acknowledgeUnscoped: args.acknowledge_unscoped }),
228
- }], consume, undefined, signal).catch((err) => { throw fieldNameInput(scopeRequiredInput(err, 'filter', true), true); }),
235
+ }, companies)], companies === undefined ? consume : page => {
236
+ verifyDocumentRows(operation, page.items, companies);
237
+ return consume({ ...page, items: projectDocumentRows(page.items, args.include_fields) });
238
+ }, undefined, signal).catch((err) => { throw fieldNameInput(scopeRequiredInput(err, 'filter', true), true); }),
229
239
  }).catch((error) => { if (error instanceof QueryExportIncompleteError)
230
240
  return undefined; throw error; });
231
241
  if (exported === undefined)
@@ -95,7 +95,8 @@ export function buildCatalog(ctx) {
95
95
  requiredArgs: r.requiredArgs,
96
96
  tier: r.tier,
97
97
  reachable,
98
- reachReason: r.reachReason,
98
+ reachReason: r.operation.startsWith('documents.') && r.effect === 'read' && tool === null
99
+ ? 'Use autotask_read with the exact operation key.' : r.reachReason,
99
100
  policyReason: reason,
100
101
  ...(r.deprecated === true ? { deprecated: true } : {}),
101
102
  };
@@ -532,6 +533,7 @@ function projectCaveats(rec) {
532
533
  * write envelope serves the created record back as `data.record` (the respond phase of
533
534
  * src/tools/write/apply.ts), so no follow-up get is needed. The pinned SDK keeps its sentence, so
534
535
  * the correction is server-composed at serve time — one template, both describe paths. */
536
+ const DOCUMENT_GET_ARGS = 'args: [id]. Use a positive signed 64-bit document ID and a canonical decimal string above Number.MAX_SAFE_INTEGER.';
535
537
  const CREATE_USAGE_FALSE = 'the full record is not returned — follow up with get where needed.';
536
538
  const CREATE_USAGE_TRUE = 'the record is read back as data.record (absent on a replay or when the vendor returns no id, null if the read-back fails).';
537
539
  /** The served `metadata.usage`, with server-specific guidance and ordering applied. */
@@ -539,6 +541,15 @@ function servedUsage(rec) {
539
541
  const u = rec.metadata?.usage;
540
542
  if (typeof u !== 'string')
541
543
  return undefined;
544
+ if (rec.resource === 'documents') {
545
+ const guidance = rec.operation === 'create' ? 'Requires account-wide run scope because the owner company does not establish the publication audience.'
546
+ : rec.operation === 'update' ? 'Uses scoped PATCH. Changing companyID or publish requires account-wide run scope. Metadata-only updates and DELETE require freshly verified category, owner, and revision.'
547
+ : rec.operation === 'delete' ? 'Confirmed scoped DELETE requires freshly verified category, owner, and revision.'
548
+ : rec.operation === 'query' ? 'A company run scope verifies the owner of every returned document. Grouped totals require account-wide scope.'
549
+ : /^(get|listByParent|getByParent|count)$/.test(rec.operation)
550
+ ? 'A company run scope restricts reads to document owners in that scope.' : '';
551
+ return `${guidance} ${u}`.trim();
552
+ }
542
553
  if (rec.id === 'document_categories.create' || rec.id === 'document_categories.update') {
543
554
  return `For creation or reparenting, put parentCategoryID in data. The choice must be active and readable even when zero. Account-wide policy and vendor permissions apply. ${u}`;
544
555
  }
@@ -567,6 +578,10 @@ function operatorWriteArgs(rec) {
567
578
  return args.join(' ');
568
579
  }
569
580
  function operatorIdDescription(rec, key) {
581
+ if (rec.resource === 'documents')
582
+ return key === 'parentId'
583
+ ? 'parentId requires a positive signed 32-bit category ID as a JSON integer or canonical decimal string.'
584
+ : 'id requires a positive signed 64-bit document ID. Use a canonical decimal string above Number.MAX_SAFE_INTEGER.';
570
585
  return rec.resource === 'knowledge_base_articles' && key === 'parentId'
571
586
  ? 'parentId requires a positive signed 32-bit category ID as a JSON integer.'
572
587
  : `${key} requires a positive safe integer JSON number.`;
@@ -579,6 +594,11 @@ function staffQueryArgs(text) {
579
594
  function servedRecord(rec) {
580
595
  const projected = { ...projectCaveats(rec) };
581
596
  delete projected.tests;
597
+ if (rec.id === 'documents.get') {
598
+ projected.inputSchema = { id: rec.inputSchema.id };
599
+ delete projected.inputSchemaStrict;
600
+ projected.examples = ['autotask_read { "operation": "documents.get", "args": [123] }'];
601
+ }
582
602
  const staffExample = staffIdReadExample(rec);
583
603
  if (staffExample !== undefined)
584
604
  projected.examples = [staffExample.example];
@@ -586,6 +606,8 @@ function servedRecord(rec) {
586
606
  const usage = servedUsage(rec);
587
607
  if (usage !== undefined && usage !== md?.usage)
588
608
  projected.metadata = { ...md, usage };
609
+ if (rec.id === 'documents.get')
610
+ projected.metadata = { ...projected.metadata, args: DOCUMENT_GET_ARGS };
589
611
  const params = rec.inputSchema.params;
590
612
  const argsText = rec.metadata?.args;
591
613
  if (rec.operation === 'query' && staffReadParentFilter(rec.resource) !== undefined) {
@@ -603,7 +625,7 @@ function servedRecord(rec) {
603
625
  const descriptor = schema[key];
604
626
  if (descriptor === undefined)
605
627
  continue;
606
- schema[key] = { ...descriptor, type: 'number', description: operatorIdDescription(rec, key) };
628
+ schema[key] = { ...descriptor, type: rec.resource === 'documents' ? 'string | number' : 'number', description: operatorIdDescription(rec, key) };
607
629
  }
608
630
  projected.inputSchema = schema;
609
631
  projected.metadata = { ...projected.metadata, args };
@@ -674,7 +696,7 @@ function summariseRecord(ctx, operation, viaTool) {
674
696
  const row = CATALOG.catalog.find((r) => r.operation === operation);
675
697
  const text = (v) => (typeof v === 'string' ? v : '');
676
698
  const cut = [];
677
- const tool = viaTool ?? toolForOp(operation);
699
+ const tool = viaTool ?? toolForOp(operation) ?? (rec.resource === 'documents' ? (rec.effect === 'read' ? 'autotask_read' : 'autotask_write') : undefined);
678
700
  return ok(`Summary of "${rec.id}" (purpose, args, usage).`, {
679
701
  operation: rec.id,
680
702
  ...(tool !== undefined ? { tool, ...toolServed(ctx, tool) } : {}),
@@ -682,7 +704,7 @@ function summariseRecord(ctx, operation, viaTool) {
682
704
  requiredArgs: row?.requiredArgs ?? [],
683
705
  args: capText(rec.operation === 'query' && staffReadParentFilter(rec.resource) !== undefined
684
706
  ? `${STAFF_COUNT_GUIDANCE} ${staffQueryArgs(text(md.args))}`
685
- : staffAttachmentArgs(rec) ?? operatorWriteArgs(rec) ?? text(md.args), SUMMARY_CAPS.args, 'args', cut),
707
+ : staffAttachmentArgs(rec) ?? operatorWriteArgs(rec) ?? (rec.id === 'documents.get' ? DOCUMENT_GET_ARGS : text(md.args)), SUMMARY_CAPS.args, 'args', cut),
686
708
  usage: capText(text(compactUsage(rec, true)), SUMMARY_CAPS.usage, 'usage', cut),
687
709
  reachable: reason === null,
688
710
  why_not: reason,
@@ -725,9 +747,10 @@ async function describeRecord(ctx, operation, viaTool, summary = false, full = f
725
747
  const reason = refusalReason(operation, rec, ctx.config, ctx.writable, ctx.write?.runScope);
726
748
  const guidance = await guidanceFor(ctx, rec, reason === null);
727
749
  const names = paramNames(operation, rec);
750
+ const tool = viaTool ?? (rec.resource === 'documents' ? toolForOp(operation) ?? (rec.effect === 'read' ? 'autotask_read' : 'autotask_write') : undefined);
728
751
  const cut = [];
729
752
  return ok(`Registry record for "${rec.id}".`, {
730
- ...(viaTool !== undefined ? { tool: viaTool, ...toolServed(ctx, viaTool) } : {}),
753
+ ...(tool !== undefined ? { tool, ...toolServed(ctx, tool) } : {}),
731
754
  operation: rec.id,
732
755
  ...(guidance !== undefined ? { guidance } : {}),
733
756
  ...(rec.effect === 'read' && viaTool === undefined && !rec.id.endsWith('.query') ? { readEnvelope: READ_ENVELOPE } : {}),
@@ -310,7 +310,7 @@ export function isKnowledgeBaseRootOperation(operation) {
310
310
  }
311
311
  export function isShapeOnlyVendorOperation(operation) {
312
312
  return operation !== undefined && (isKnowledgeBaseRootOperation(operation)
313
- || /^(document_categories|inventory_items|inventory_locations|internal_locations|shipping_types|organizational_resources|resource_daily_availabilities)\./.test(operation)
313
+ || /^(documents|document_categories|inventory_items|inventory_locations|internal_locations|shipping_types|organizational_resources|resource_daily_availabilities)\./.test(operation)
314
314
  || /^products\.(get|fetchRecord|fetchByIds)$/.test(operation));
315
315
  }
316
316
  /** A vendor failure's canonical status code, also used in transport audit logs. */
@@ -330,7 +330,7 @@ export function resolveFaultCode(resource, error) {
330
330
  export function shapeOnlyVendorCode(operation, httpStatus, error) {
331
331
  if (!isShapeOnlyVendorOperation(operation))
332
332
  return undefined;
333
- const typedFault = operation?.startsWith('document_categories.') === true || isStaffReadOperation(operation);
333
+ const typedFault = operation?.startsWith('documents.') === true || operation?.startsWith('document_categories.') === true || isStaffReadOperation(operation);
334
334
  if (typedFault && error instanceof ResponseRejectedError)
335
335
  return error.code;
336
336
  const vendorError = error?.vendorError;
@@ -406,21 +406,24 @@ export function typedErrorPayload(err, correlationId, secrets = [], directIdenti
406
406
  // SDK's own deterministic text (bounded as before).
407
407
  const knowledgeBase = isKnowledgeBaseRootOperation(operation);
408
408
  const inventoryLocation = operation?.startsWith('inventory_locations.') === true;
409
- if (shapeOnlyVendorError && code === 'NOT_FOUND' && (knowledgeBase || operation?.endsWith('.get') === true)) {
410
- payload.message = operation === 'knowledge_base_articles.get'
411
- ? 'No published article was visible to this API user at the requested ID.'
412
- : knowledgeBase
413
- ? 'No Knowledge Base record was visible to this API user at the requested ID.'
414
- : operation === 'inventory_locations.get'
415
- ? 'No inventory location was visible to this API user at the requested ID.'
416
- : 'No record was visible to this API user at the requested ID.';
409
+ const document = operation?.startsWith('documents.') === true;
410
+ if (shapeOnlyVendorError && code === 'NOT_FOUND' && (knowledgeBase || document || operation?.endsWith('.get') === true)) {
411
+ payload.message = document ? 'No published document was visible to this API user at the requested route.'
412
+ : operation === 'knowledge_base_articles.get'
413
+ ? 'No published article was visible to this API user at the requested ID.'
414
+ : knowledgeBase
415
+ ? 'No Knowledge Base record was visible to this API user at the requested ID.'
416
+ : operation === 'inventory_locations.get'
417
+ ? 'No inventory location was visible to this API user at the requested ID.'
418
+ : 'No record was visible to this API user at the requested ID.';
417
419
  }
418
420
  else if (entityPermissionRefusal) {
419
421
  payload.message = operation?.startsWith('document_categories.') === true
420
422
  ? 'Autotask refused permission for this document category read (HTTP 403).'
421
- : 'Autotask refused permission for this staff read (HTTP 403).';
423
+ : document ? 'Autotask refused permission for this Documents read (HTTP 403).'
424
+ : 'Autotask refused permission for this staff read (HTTP 403).';
422
425
  }
423
- else if ((operation?.startsWith('document_categories.') === true || isStaffReadOperation(operation)) && err instanceof ResponseRejectedError) {
426
+ else if ((document || operation?.startsWith('document_categories.') === true || isStaffReadOperation(operation)) && err instanceof ResponseRejectedError) {
424
427
  payload.message = code === 'RESPONSE_TOO_LARGE' ? 'The Autotask response exceeded the SDK response size limit.'
425
428
  : code === 'REDIRECT_BLOCKED' ? 'The SDK blocked an Autotask response redirect.'
426
429
  : 'The SDK rejected the Autotask response under its response policy.';
@@ -140,6 +140,7 @@ export function createMcpServerFactory(config, log, options = {}) {
140
140
  : configForToken(config, entry);
141
141
  const scope = readRequestScope(headers);
142
142
  const resolved = resolver.resolve(scope);
143
+ const runScope = tokens === undefined ? config.AUTOTASK_RUN_SCOPE : entry?.runScope;
143
144
  // One correlation id per serving unit: it rides every log line and every served error of
144
145
  // this request (mandatory on errors).
145
146
  const correlationId = randomUUID();
@@ -152,13 +153,14 @@ export function createMcpServerFactory(config, log, options = {}) {
152
153
  log,
153
154
  correlationId,
154
155
  ops: options.ops ?? defaultToolOps,
156
+ ...(runScope === undefined ? {} : { runScope }),
155
157
  ...(requestConfig.AUTOTASK_PROFILE === 'operator' && write !== undefined
156
158
  ? {
157
159
  write: {
158
160
  runtime: entry?.writeOperations === undefined ? write
159
161
  : { ...write, loaded: restrictWritePolicy(write.loaded, entry.writeOperations) },
160
162
  principal: identity !== undefined ? identity.principal : (entry?.principal ?? config.AUTOTASK_PRINCIPAL),
161
- runScope: tokens === undefined ? config.AUTOTASK_RUN_SCOPE : entry?.runScope,
163
+ runScope,
162
164
  ...(identity?.clientId !== undefined ? { clientId: identity.clientId } : {}),
163
165
  },
164
166
  }
@@ -3,6 +3,8 @@
3
3
  * Two tools, by risk (#302): `autotask_apply` takes plans that hit no hard rule, `autotask_apply_destructive`
4
4
  * the ones that do; the transport decides who approves (stdio: this server, HTTP: the client or gateway).
5
5
  */
6
+ import { documentUpdateScopeReason } from '../../policy.js';
7
+ import { documentId, isDocumentOwner } from '../documents.js';
6
8
  import { APPLY_INPUT, APPLY_PARSE, closedInput } from '../schemas.js';
7
9
  import { projectTimeEntryVerification } from '../time-entry-verification.js';
8
10
  import { writeDeps } from './common.js';
@@ -24,7 +26,7 @@ import { COOLDOWN_MINUTES } from '../../write/store.js';
24
26
  import { Cancelled, tenantIdentity, answer, applyToolFor, isNotFound, reason } from './common.js';
25
27
  import { SHAPE_ARGS, parseArgs } from './parse.js';
26
28
  import { ci } from './payload.js';
27
- import { approvedWriteOptions, documentCategoryGuardReads, documentCategoryReadFault, getIds, takeSnapshot } from './snapshot.js';
29
+ import { approvedWriteOptions, documentCategoryGuardReads, documentCategoryReadFault, documentReadFault, getIds, takeSnapshot } from './snapshot.js';
28
30
  import { unresolvedReason, deriveFacts } from './facts.js';
29
31
  import { honestError, notPersistedAnswer, outcomeAnswer, vendorRefusal } from './outcome.js';
30
32
  const inventoryItemGuardReads = ['products.get', 'inventory_locations.get', 'inventory_items.get'];
@@ -37,7 +39,7 @@ function documentCategoryLocalRefusal(operation, error) {
37
39
  return error.operation === undefined || error.operation === operation || documentCategoryGuardReads.includes(error.operation);
38
40
  }
39
41
  function usesApprovalHandle(resource) {
40
- return resource === 'inventory_items' || resource === 'document_categories';
42
+ return resource === 'inventory_items' || resource === 'document_categories' || resource === 'documents';
41
43
  }
42
44
  function inventoryReadUnavailable(operation, error) {
43
45
  if (!isAutotaskError(error) || error.vendorError !== undefined)
@@ -73,7 +75,7 @@ function staleInventoryItemGuard(operation, error) {
73
75
  return inventoryReadUnavailable(operation, error);
74
76
  }
75
77
  function hasStrictReadBack(resource) {
76
- return resource === 'inventory_locations' || resource === 'inventory_items' || resource === 'document_categories';
78
+ return resource === 'inventory_locations' || resource === 'inventory_items' || resource === 'document_categories' || resource === 'documents';
77
79
  }
78
80
  /**
79
81
  * Who must approve one apply: `person` (stdio form or grant), `policy:unattended`, `client` (HTTP), or
@@ -220,7 +222,7 @@ async function execute(a, confirmation) {
220
222
  return identityRefusal;
221
223
  }
222
224
  catch (err) {
223
- if (plan.targets.resource !== 'document_categories' || !isImpersonationValidationDenial(err))
225
+ if (!['document_categories', 'documents'].includes(plan.targets.resource) || !isImpersonationValidationDenial(err))
224
226
  throw err;
225
227
  return snapshotDrift(a, 'Autotask refused the impersonation validation read. Preview again.', {
226
228
  code: errorFromStatus(err.httpStatus, undefined).code, httpStatus: err.httpStatus,
@@ -252,6 +254,12 @@ async function execute(a, confirmation) {
252
254
  ? { code: shapeOnlyVendorCode(err.operation, err.httpStatus, err) ?? err.code, httpStatus: err.httpStatus } : undefined;
253
255
  return snapshotDrift(a, 'The fresh document category could not be verified. Preview again.', fault);
254
256
  }
257
+ if (record.resource === 'documents' && documentReadFault(err, duplicateFields !== undefined)) {
258
+ releaseClientOnError(ctx, err);
259
+ const fault = err.category === 'auth' || err instanceof ResponseRejectedError
260
+ ? { code: shapeOnlyVendorCode(err.operation, err.httpStatus, err) ?? err.code, httpStatus: err.httpStatus } : undefined;
261
+ return snapshotDrift(a, 'The document owner, category, or revision could not be verified. No mutation was sent. Preview again.', fault);
262
+ }
255
263
  if (record.resource === 'inventory_items' && (isNotFound(err) || inventoryReadUnavailable(record.id, err))) {
256
264
  return snapshotDrift(a, 'the target changed since the preview; preview again');
257
265
  }
@@ -260,7 +268,9 @@ async function execute(a, confirmation) {
260
268
  if (!('code' in snap) && snap.unresolved.length > 0)
261
269
  return refused('denied', 'stop', unresolvedReason(snap.unresolved), plan);
262
270
  if ('code' in snap) {
263
- return snapshotDrift(a, 'the target changed since the preview; preview again');
271
+ return snapshotDrift(a, record.resource === 'documents'
272
+ ? `${snap.detail} No mutation was sent. Preview again.`
273
+ : 'the target changed since the preview; preview again');
264
274
  }
265
275
  // Issue #106: evaluate FRESH facts (rebuilt from the re-read, never the stored ones) after the re-read.
266
276
  const fresh = freshFacts(snap);
@@ -268,6 +278,9 @@ async function execute(a, confirmation) {
268
278
  // The pin has explicit duplicate/cap refusals; other changed facts retain the drift contract.
269
279
  if (freshDecision.decision === 'deny' && freshDecision.rule === PIN_RULE)
270
280
  return refused('denied', 'stop', freshDecision.reasons[0], plan);
281
+ if (record.resource === 'documents' && freshDecision.decision === 'deny' && freshDecision.reasons[0]?.code === 'DUPLICATE_EXISTS') {
282
+ return snapshotDrift(a, 'A document now matches the configured deduplication fields, category, and owner. No mutation was sent. Preview again.');
283
+ }
271
284
  // the human confirmed these facts; different fresh facts are drift, and the old confirmation is unusable
272
285
  if (!matchesApproval(snap, fresh) || (confirmation !== undefined && confirmation.planHash !== plan.planHash)) {
273
286
  return snapshotDrift(a, 'the facts behind this plan changed since the confirmation; preview again');
@@ -319,7 +332,10 @@ async function execute(a, confirmation) {
319
332
  const approvedReplacement = plan.op === 'document_categories.update' && sent.entry.state === 'succeeded'
320
333
  && categoryTarget !== undefined && parsed.data !== undefined
321
334
  ? documentCategoryReplacementFields({ ...categoryTarget }, parsed.data) : undefined;
322
- return respond(a, { record, shape, entry: sent.entry, error: sent.error, moveResult: sent.moveResult, callResult: sent.callResult, approvedReplacement });
335
+ const readBackOwner = record.resource === 'documents' ? parsed.data?.companyID ?? snap.expectedDocumentOwnerID : undefined;
336
+ const previousOwner = snap.expectedDocumentOwnerID;
337
+ return respond(a, { record, shape, entry: sent.entry, error: sent.error, moveResult: sent.moveResult, callResult: sent.callResult, approvedReplacement,
338
+ ...(isDocumentOwner(readBackOwner) ? { documentOwners: { expected: readBackOwner, previous: previousOwner } } : {}) });
323
339
  }
324
340
  /** `apply_start`, then the one SDK write under the cap. Never returns a ToolReturn: the outcome is always a ledger entry. */
325
341
  async function send(a, s) {
@@ -342,6 +358,9 @@ async function send(a, s) {
342
358
  let moveResult;
343
359
  let callResult;
344
360
  const categoryWrite = documentCategoryWrites.includes(plan.op);
361
+ const documentWrite = record.resource === 'documents';
362
+ let documentAdmitted = false;
363
+ const moveSource = shape === 'move' && typeof plan.targets.id === 'number' ? { sourceId: plan.targets.id } : {};
345
364
  let dispatchBlock;
346
365
  try {
347
366
  // ponytail: past the cap the write keeps running and its late answer is not recorded; the
@@ -350,10 +369,15 @@ async function send(a, s) {
350
369
  const stamp = snap.lastModifiedDate ?? (shape === 'move' ? ci(snap.current ?? {}, 'lastModifiedDateTime') : undefined);
351
370
  const staleOpts = typeof stamp === 'string' ? { lastModifiedDate: stamp } : {};
352
371
  const write = () => invoke(ctx.client, plan.op, plan.args, { dryRun: false, ...confirm, ...approvedWriteOptions(snap), ...staleOpts, maxRetries: 0 });
353
- const pending = categoryWrite ? ctx.client.withDocumentCategoryMutationDispatchCheck(() => {
372
+ const check = () => {
354
373
  dispatchBlock = store.blocked();
374
+ if (documentWrite)
375
+ documentAdmitted = dispatchBlock === undefined;
355
376
  return dispatchBlock === undefined;
356
- }, write) : write();
377
+ };
378
+ const client = ctx.client;
379
+ const pending = documentWrite ? client.withDocumentMutationDispatchCheck(check, write)
380
+ : categoryWrite ? client.withDocumentCategoryMutationDispatchCheck(check, write) : write();
357
381
  const result = await Promise.race([pending, capped]);
358
382
  if (result === 'cap') {
359
383
  entry = { ...base, state: 'unknown', at: now(), outcome: { code: 'APPLY_TIMEOUT' } };
@@ -365,14 +389,14 @@ async function send(a, s) {
365
389
  const clean = newId !== undefined && (m?.status === 'moved' || m?.status === 'moved_source_absent' || m?.status === 'moved_manual_delete');
366
390
  // the contract is a MoveResult or a thrown refusal: anything else is NOT recorded as a success (fail closed, never re-sent)
367
391
  entry = !clean
368
- ? { ...base, state: 'unknown', at: now(), outcome: { code: 'MOVE_UNKNOWN', retryable: false, ...(plan.targets.id !== undefined ? { sourceId: plan.targets.id } : {}), ...(newId !== undefined ? { newId } : {}) } }
392
+ ? { ...base, state: 'unknown', at: now(), outcome: { code: 'MOVE_UNKNOWN', retryable: false, ...moveSource, ...(newId !== undefined ? { newId } : {}) } }
369
393
  : {
370
394
  ...base,
371
395
  state: 'succeeded',
372
396
  at: now(),
373
397
  outcome: {
374
398
  ...(newId !== undefined ? { id: newId, newId } : {}),
375
- ...(plan.targets.id !== undefined ? { sourceId: plan.targets.id } : {}),
399
+ ...moveSource,
376
400
  ...(m?.status === 'moved_manual_delete' ? { code: 'MOVE_MANUAL_DELETE' } : m?.status === 'moved_source_absent' ? { code: 'MOVE_SOURCE_ABSENT' } : {}),
377
401
  },
378
402
  };
@@ -389,7 +413,7 @@ async function send(a, s) {
389
413
  at: now(),
390
414
  outcome: createdId === undefined ? {} : {
391
415
  id: createdId,
392
- ...(shape !== 'delete' && hasStrictReadBack(record.resource)
416
+ ...(!shape.startsWith('delete') && hasStrictReadBack(record.resource)
393
417
  ? { code: 'READBACK_UNVERIFIED' }
394
418
  : {}),
395
419
  },
@@ -417,13 +441,26 @@ async function send(a, s) {
417
441
  ...base,
418
442
  state: 'unknown',
419
443
  at: now(),
420
- outcome: { code: refusal.status === 'partial' ? 'MOVE_PARTIAL' : 'MOVE_UNKNOWN', retryable: false, ...(plan.targets.id !== undefined ? { sourceId: plan.targets.id } : {}), ...(typeof refusal.newId === 'number' ? { newId: refusal.newId } : {}) },
444
+ outcome: { code: refusal.status === 'partial' ? 'MOVE_PARTIAL' : 'MOVE_UNKNOWN', retryable: false, ...moveSource, ...(typeof refusal.newId === 'number' ? { newId: refusal.newId } : {}) },
421
445
  };
422
446
  }
423
447
  else if (err instanceof MoveRefusedError) {
424
448
  // a hard refusal or a rolled-back attempt: nothing is left behind, and a re-send would be refused again
425
449
  entry = { ...base, state: 'failed', at: now(), outcome: { code: err.code ?? 'MOVE_REFUSED', retryable: false } };
426
450
  }
451
+ else if (documentWrite && !documentAdmitted && isAutotaskError(err)) {
452
+ // The SDK hook is after every guard and transport admission. Even a GET error carrying
453
+ // an HTTP status is a proven no-send here. A transient read leaves the handle retryable.
454
+ releaseClientOnError(ctx, err);
455
+ const retryable = err.retryable;
456
+ entry = {
457
+ ...base, state: 'failed', at: now(),
458
+ ...(!retryable ? { invalidatedPlan: plan.handle } : {}),
459
+ outcome: { code: shapeOnlyVendorCode(err.operation ?? plan.op, err.httpStatus, err) ?? err.code, retryable,
460
+ ...(err.httpStatus !== undefined ? { httpStatus: err.httpStatus } : {}) },
461
+ };
462
+ Object.assign(err, { notSent: true });
463
+ }
427
464
  else if (record.resource === 'inventory_items' && staleInventoryItemGuard(record.id, err)) {
428
465
  entry = { ...base, state: 'failed', at: now(), invalidatedPlan: plan.handle, outcome: { code: 'STALE_OBJECT', retryable: false } };
429
466
  }
@@ -500,7 +537,7 @@ function recordResult(a, entry, confirmation) {
500
537
  store.releaseOpLock();
501
538
  }
502
539
  // A recorded dispatch denial has already accounted for the holder check and sent no mutation.
503
- if (plan.targets.resource === 'document_categories' && entry.state === 'failed' && entry.outcome?.httpStatus === undefined
540
+ if (['document_categories', 'documents'].includes(plan.targets.resource) && entry.state === 'failed' && entry.outcome?.httpStatus === undefined
504
541
  && (entry.outcome?.code === 'KILL_SWITCH' || entry.outcome?.code === 'STATE_UNAVAILABLE'))
505
542
  return;
506
543
  // A removed holder stops this process. A kill switch or a transient holder read failure
@@ -559,13 +596,26 @@ function documentCategoryReplacementFields(current, patch) {
559
596
  const merged = { ...current, ...patch };
560
597
  return Object.fromEntries(['name', 'description', 'parentCategoryID'].filter(field => Object.hasOwn(merged, field) && merged[field] !== undefined).map(field => [field, merged[field]]));
561
598
  }
562
- async function readStrictApply(a, resource, id, sent = a.plan.args.at(-1)) {
563
- const operation = `${resource}.get`;
564
- const ids = getIds(a.ctx, resource, a.plan.targets.parentId, id);
599
+ async function readStrictApply(a, resource, id, sent = a.plan.args.at(-1), owners) {
600
+ const operation = resource === 'documents' ? 'documents.getByParent' : `${resource}.get`;
601
+ const ids = resource === 'documents' ? [a.plan.targets.parentId, id] : getIds(a.ctx, resource, a.plan.targets.parentId, id);
565
602
  const exactDecimal = resource !== 'inventory_locations';
566
603
  let missed = [];
567
- const back = await readOneItem(a.ctx, operation, ids, undefined, { fresh: true }, exactDecimal
604
+ const back = await readOneItem(a.ctx, operation, ids, undefined, resource === 'documents' ? undefined : { fresh: true }, exactDecimal
568
605
  ? (raw) => {
606
+ if (resource === 'documents') {
607
+ const row = raw;
608
+ if (documentId(row?.id) !== documentId(id) || row?.documentCategoryID !== a.plan.targets.parentId || owners === undefined) {
609
+ throw new Error('Document read-back did not establish the approved identity, category, and owner');
610
+ }
611
+ if (row?.companyID !== owners.expected) {
612
+ if (owners.previous !== undefined && row?.companyID === owners.previous) {
613
+ missed = ['companyID'];
614
+ return null;
615
+ }
616
+ throw new Error('Document read-back did not establish the approved owner');
617
+ }
618
+ }
569
619
  missed = strictFieldMisses(sent, raw, id, true);
570
620
  return markResult(raw, a.ctx.untrustedFields(operation));
571
621
  }
@@ -630,7 +680,7 @@ async function respond(a, r) {
630
680
  try {
631
681
  const id = entry.outcome.id;
632
682
  if (entry.outcome.code === 'READBACK_UNVERIFIED') {
633
- const readBack = () => readStrictApply(a, record.resource, id);
683
+ const readBack = () => readStrictApply(a, record.resource, id, undefined, r.documentOwners);
634
684
  const back = record.resource === 'inventory_locations' ? await readBack() : await recheckReadBack(readBack);
635
685
  if (back.missed.length > 0)
636
686
  return await reportPersistedMiss(a, entry, back.missed, back.result);
@@ -670,7 +720,7 @@ async function respond(a, r) {
670
720
  const strict = hasStrictReadBack(record.resource);
671
721
  const readBack = async () => {
672
722
  if (strict)
673
- return readStrictApply(a, record.resource, id, r.approvedReplacement);
723
+ return readStrictApply(a, record.resource, id, r.approvedReplacement, r.documentOwners);
674
724
  const { result } = await readOneItem(ctx, `${record.resource}.get`, getIds(ctx, record.resource, plan.targets.parentId, id), undefined, { fresh: true });
675
725
  const stored = result !== null && typeof result === 'object' ? stripUntrustedDeep(result) : undefined;
676
726
  const missed = stored === undefined || sent === null || typeof sent !== 'object' ? [] : notPersistedFields(sent, stored);
@@ -679,6 +729,8 @@ async function respond(a, r) {
679
729
  const back = await recheckReadBack(readBack);
680
730
  if (back.missed.length === 0)
681
731
  return await reportVerifiedReadBack(a, entry, back.result);
732
+ if (record.resource === 'documents' && back.result === null)
733
+ return outcomeAnswer(plan, entry, { replayed: false });
682
734
  // record the miss: the latest ledger line wins, so a replay answers the same reasons.
683
735
  return await reportPersistedMiss(a, entry, back.missed, back.result ?? null);
684
736
  }
@@ -725,9 +777,23 @@ export function buildApply(ctx, destructive = false) {
725
777
  if (readBack === 'time_entry_verification_v1' && plan.op !== 'time_entries.create') {
726
778
  return refused('error', 'supply_input', reason('INPUT_INVALID', 'readBack time_entry_verification_v1 requires time_entries.create', 'readBack'), plan);
727
779
  }
728
- const scopeRefusal = writeScopeReason(plan.op, hardRuleFor(plan.op, effective.record(plan.op)).hazards, w.runScope);
780
+ const scopeRefusal = writeScopeReason(plan.op, hardRuleFor(plan.op, effective.record(plan.op)).hazards, w.runScope)
781
+ ?? documentUpdateScopeReason(plan.op, plan.args.at(-1), w.runScope);
729
782
  if (scopeRefusal !== undefined)
730
783
  return refused('denied', 'stop', scopeRefusal, plan);
784
+ if (plan.targets.resource === 'documents') {
785
+ const mode = loaded.table.get(plan.op)?.mode;
786
+ if (mode === undefined || mode === 'deny') {
787
+ return refused('denied', 'stop', reason('OP_NOT_ALLOWED', 'The effective write policy does not admit this Documents operation.'), plan);
788
+ }
789
+ const stale = staleAnswer(a);
790
+ if (stale !== undefined)
791
+ return stale;
792
+ const scope = w.runScope;
793
+ if (scope === undefined || ('companyIds' in scope && !plan.facts.companyIds.every(owner => scope.companyIds.includes(owner)))) {
794
+ return refused('denied', 'stop', reason('TARGET_NOT_IN_SCOPE', 'The approved document owner company is outside the effective write scope.'), plan);
795
+ }
796
+ }
731
797
  // Who approves (#302). HTTP: the client or gateway did, so the server never asks. stdio: the
732
798
  // mode decides; a person's answer runs over the LOADED plan and OUTSIDE the apply lock (it must
733
799
  // never hold it). A ledger hit that ends the apply (a replay) answers in execute() without asking;
@@ -96,7 +96,7 @@ export function outcomeAnswer(plan, entry, extra) {
96
96
  }
97
97
  if (entry.state === 'failed') {
98
98
  const block = entry.outcome?.code;
99
- if (plan.targets.resource === 'document_categories' && entry.outcome?.httpStatus === undefined
99
+ if (['document_categories', 'documents'].includes(plan.targets.resource) && entry.outcome?.httpStatus === undefined
100
100
  && (block === 'KILL_SWITCH' || block === 'STATE_UNAVAILABLE')) {
101
101
  const retryable = entry.outcome?.retryable === true;
102
102
  const detail = block === 'KILL_SWITCH' ? 'Writes are stopped by the kill switch.'
@@ -104,6 +104,13 @@ export function outcomeAnswer(plan, entry, extra) {
104
104
  const action = retryable ? 'Retry this approval shortly.' : 'Preview again once writes are available.';
105
105
  return answer(retryable ? 'error' : 'denied', retryable ? 'retry' : 'stop', [reason(block, `${detail} No mutation was sent. ${action}`)], base, { ...meta, retryable });
106
106
  }
107
+ if (plan.targets.resource === 'documents' && entry.invalidatedPlan === plan.handle) {
108
+ const { code = 'STATE_DRIFT', httpStatus } = entry.outcome ?? {};
109
+ const auth = code === 'UNAUTHORIZED' || code === 'FORBIDDEN';
110
+ const detail = auth ? `Autotask refused access during Documents preflight (HTTP ${httpStatus}). ` : '';
111
+ return answer('error', 'repreview', [reason(auth ? 'WRITE_FAILED' : 'STATE_DRIFT', detail + 'No mutation was sent. Verify the document owner, category, and revision, then preview again.')], { ...base, error: { error: true, code, ...(httpStatus !== undefined ? { httpStatus } : {}),
112
+ notSent: true, retryable: false, nextAction: 'repreview' } }, meta);
113
+ }
107
114
  if (plan.targets.resource === 'document_categories' && entry.invalidatedPlan === plan.handle) {
108
115
  const status = entry.outcome?.httpStatus;
109
116
  const code = entry.outcome?.code ?? 'WRITE_FAILED';
@@ -2,6 +2,7 @@
2
2
  import { validateDispatchArgs } from 'node-autotask/operations';
3
3
  import { stripUntrustedDeep } from 'node-autotask/untrusted';
4
4
  import { hashOf } from '../../write/canonical.js';
5
+ import { documentCategoryId, documentId } from '../documents.js';
5
6
  import { reason } from './common.js';
6
7
  import { caseDuplicate, sanitisedArtefact, cleanPayload, leftoverCombiningMark } from './payload.js';
7
8
  // ---------------------------------------------------------------------------
@@ -130,6 +131,19 @@ export function parseArgs(shape, record, raw) {
130
131
  out.push(data);
131
132
  continue;
132
133
  }
134
+ if (record.resource === 'documents' && (name === 'parentId' || name === 'id')) {
135
+ const id = name === 'parentId' ? documentCategoryId(raw[i]) : documentId(raw[i]);
136
+ if (id === undefined)
137
+ return reason('INPUT_INVALID', name === 'parentId'
138
+ ? 'parentId must be a positive signed 32-bit category ID'
139
+ : 'id must be a positive signed 64-bit document ID. Use a canonical decimal string above Number.MAX_SAFE_INTEGER.', `args.${i}`);
140
+ if (name === 'parentId' && typeof id === 'number')
141
+ targets.parentId = id;
142
+ else
143
+ targets.id = id;
144
+ out.push(id);
145
+ continue;
146
+ }
133
147
  // a parent id may be 0 (a contact on company 0); the snapshot refuses it before any read unless the parent is companies
134
148
  if (typeof v !== 'number' || !Number.isSafeInteger(v) || v < 0 || (v === 0 && name !== 'parentId')) {
135
149
  return reason('INPUT_INVALID', `args[${i}] (${name}) must be a numeric id; write targets are ids, never names (resolve a name with autotask_resolve first)`, `args.${i}`);
@@ -5,7 +5,7 @@ import { describeWrite } from 'node-autotask/operations';
5
5
  import { toolError } from '../dispatch.js';
6
6
  import { abortedResult } from '../results/errors.js';
7
7
  import { cleanUntrustedText, markResult } from '../results/untrusted.js';
8
- import { assertOperationPermitted } from '../../policy.js';
8
+ import { assertOperationPermitted, documentUpdateScopeReason } from '../../policy.js';
9
9
  import { WRITE_INPUT, closedInput } from '../schemas.js';
10
10
  import { planHashOf } from '../../write/canonical.js';
11
11
  import { dedupFor, evaluate, pinAudit, writeScopeReason } from '../../write/evaluate.js';
@@ -274,7 +274,7 @@ async function execute(ctx, args, signal, ownerTenantId) {
274
274
  return answer('error', 'supply_input', [parsed], { operation: op });
275
275
  const a = { record, shape, parsed, rule };
276
276
  // Reject operations whose company scope cannot admit any target before reading vendor records.
277
- const scopeRefusal = writeScopeReason(op, hard.hazards, w.runScope);
277
+ const scopeRefusal = writeScopeReason(op, hard.hazards, w.runScope) ?? documentUpdateScopeReason(op, parsed.data, w.runScope);
278
278
  if (scopeRefusal !== undefined) {
279
279
  audit('deny', [scopeRefusal], undefined, parsed.targets);
280
280
  return answer('denied', 'stop', [scopeRefusal], { operation: op, targets: parsed.targets });
@@ -304,8 +304,8 @@ async function execute(ctx, args, signal, ownerTenantId) {
304
304
  audit('deny', rs, undefined, parsed.targets);
305
305
  return answer('denied', 'stop', rs, { operation: op, targets: parsed.targets });
306
306
  }
307
- // Scope must precede an SDK move refusal, whose message may name records outside this run.
308
- if (shape === 'move') {
307
+ // Scope precedes SDK move diagnostics. An observed Documents match makes further dry-run reads unnecessary.
308
+ if (shape === 'move' || (op === 'documents.create' && snap.duplicates > 0)) {
309
309
  const facts = deriveFacts({ store, op, record, shape, parsed, snap });
310
310
  const decision = evaluate(loaded, facts, w.runScope, store.counters(op, w.runtime.now()));
311
311
  if (decision.decision === 'deny') {
@@ -328,6 +328,11 @@ async function execute(ctx, args, signal, ownerTenantId) {
328
328
  audit('denied', rs, undefined, parsed.targets);
329
329
  return answer('error', 'repreview', rs, { operation: op, targets: parsed.targets });
330
330
  }
331
+ if (record.resource === 'documents' && err instanceof StaleObjectError) {
332
+ const rs = [reason('STATE_DRIFT', 'The document owner or revision changed while constructing the preview. Preview again.')];
333
+ audit('denied', rs, undefined, parsed.targets);
334
+ return answer('error', 'repreview', rs, { operation: op, targets: parsed.targets });
335
+ }
331
336
  if (!(err instanceof MoveRefusedError))
332
337
  throw err;
333
338
  const rs = [reason('MOVE_REFUSED', `${err.code ?? 'MOVE_REFUSED'}: ${err.message}`)];
@@ -37,8 +37,9 @@ export interface Snapshot {
37
37
  /** References whose record could not be read: the write is refused. */
38
38
  unresolved: string[];
39
39
  current?: Record<string, unknown>;
40
- /** The article's approved revision token, compared by the SDK's scoped write guard. */
40
+ /** The approved revision token compared by the SDK scoped write guard. */
41
41
  lastModifiedDate?: string;
42
+ expectedDocumentOwnerID?: number;
42
43
  /** Approved inventory facts rechecked by the SDK while it plans or sends the mutation. */
43
44
  expectedInventoryFacts?: ExpectedInventoryFacts;
44
45
  /** Fresh facts passed to the SDK guard without adding them to the stored plan. */
@@ -53,6 +54,7 @@ export interface Snapshot {
53
54
  export declare function approvedWriteOptions(snap: Snapshot): InvokeOptions;
54
55
  export declare const documentCategoryGuardReads: string[];
55
56
  export declare function documentCategoryReadFault(error: unknown, includeDuplicateQuery?: boolean): error is AutotaskError;
57
+ export declare function documentReadFault(error: unknown, includeDuplicateQuery?: boolean): error is AutotaskError;
56
58
  /**
57
59
  * The generic `call` snapshot (issue #191): there is no known target/data signature, so the record's
58
60
  * own declared arguments decide what is read. A named id (`id`, `sourceId`, `sourceContactId`) is the
@@ -2,6 +2,7 @@
2
2
  import { relationshipMap } from 'node-autotask/operations';
3
3
  import { AutotaskConfigError, AutotaskError, inventoryItemGuardFacts, isAutotaskError, NotFoundError, ResponseRejectedError, } from 'node-autotask';
4
4
  import { writeShape } from '../../write/hard-rules.js';
5
+ import { documentId, isDocumentOwner } from '../documents.js';
5
6
  import { assertOperationPermitted } from '../../policy.js';
6
7
  import { Cancelled, reason, isNotFound } from './common.js';
7
8
  import { CALL_COMPANY_ARGS, CALL_ID_ARGS, asIdOrZero } from './parse.js';
@@ -58,9 +59,10 @@ export function getIds(ctx, resource, parentId, id) {
58
59
  return parentId !== undefined && !hasSimpleGet(resource, ctx) ? [parentId, id] : [id];
59
60
  }
60
61
  export function approvedWriteOptions(snap) {
61
- const { lastModifiedDate, expectedInventoryFacts, expectedDocumentCategoryFacts } = snap;
62
+ const { lastModifiedDate, expectedInventoryFacts, expectedDocumentCategoryFacts, expectedDocumentOwnerID } = snap;
62
63
  return {
63
64
  ...(lastModifiedDate !== undefined ? { lastModifiedDate } : {}),
65
+ ...(expectedDocumentOwnerID !== undefined ? { expectedDocumentOwnerID } : {}),
64
66
  ...(expectedInventoryFacts !== undefined ? { expectedInventoryFacts } : {}),
65
67
  ...(expectedDocumentCategoryFacts !== undefined ? { expectedDocumentCategoryFacts } : {}),
66
68
  };
@@ -68,11 +70,18 @@ export function approvedWriteOptions(snap) {
68
70
  class SnapshotScopeUnresolved extends Error {
69
71
  }
70
72
  export const documentCategoryGuardReads = ['document_categories.get', 'document_categories.getFieldInfo'];
73
+ const documentGuardReads = ['documents.getByParent', 'documents.getFieldInfo', 'document_categories.get', 'companies.get'];
71
74
  export function documentCategoryReadFault(error, includeDuplicateQuery = false) {
75
+ return guardedReadFault(error, documentCategoryGuardReads, includeDuplicateQuery ? 'document_categories.query' : undefined);
76
+ }
77
+ export function documentReadFault(error, includeDuplicateQuery = false) {
78
+ return guardedReadFault(error, documentGuardReads, includeDuplicateQuery ? 'documents.query' : undefined);
79
+ }
80
+ function guardedReadFault(error, reads, duplicateQuery) {
72
81
  if (!isAutotaskError(error))
73
82
  return false;
74
- const guardRead = documentCategoryGuardReads.includes(error.operation ?? '');
75
- if (!guardRead && !(includeDuplicateQuery && error.operation === 'document_categories.query'))
83
+ const guardRead = reads.includes(error.operation ?? '');
84
+ if (!guardRead && !(duplicateQuery !== undefined && error.operation === duplicateQuery))
76
85
  return false;
77
86
  const status = error.httpStatus;
78
87
  if (error.category === 'auth' && (status === 401 || status === 403))
@@ -86,6 +95,81 @@ export function documentCategoryReadFault(error, includeDuplicateQuery = false)
86
95
  return error.vendorError === undefined && (status === undefined || (status >= 200 && status < 300))
87
96
  && (error instanceof AutotaskConfigError || ['INVALID_RESPONSE', 'EMPTY_RESPONSE', 'UNEXPECTED_CONTENT_TYPE'].includes(error.code));
88
97
  }
98
+ function documentRevision(value) {
99
+ if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})?$/.test(value)
100
+ || !Number.isFinite(Date.parse(value)))
101
+ return false;
102
+ const day = value.slice(0, 10);
103
+ return new Date(`${day}T00:00:00Z`).toISOString().slice(0, 10) === day && value.slice(11, 13) !== '24';
104
+ }
105
+ async function takeDocumentSnapshot(ctx, record, parsed, duplicateFields, signal) {
106
+ const { targets: { parentId, id }, data } = parsed;
107
+ const parent = await parentOf(record.resource);
108
+ if (parent === undefined || parentId === undefined)
109
+ return reason('TARGET_NOT_IN_SCOPE', 'Could not establish the DocumentCategories route.');
110
+ const read = async (operation, args) => {
111
+ const row = await ctx.ops.invokeRead(ctx.client, operation, args, operation.endsWith('.get') ? { fresh: true } : undefined, signal);
112
+ if (row === undefined)
113
+ throw new Cancelled();
114
+ return row;
115
+ };
116
+ const current = id === undefined ? null : await read('documents.getByParent', [parentId, id]);
117
+ const currentOwner = current?.companyID;
118
+ const revision = current?.lastModifiedDateTime;
119
+ if (id !== undefined && (documentId(current?.id) !== id || current?.[parent.field] !== parentId
120
+ || !isDocumentOwner(currentOwner) || !documentRevision(revision))) {
121
+ return reason('TARGET_NOT_IN_SCOPE', 'The scoped item did not establish the document ID, category, owner company, and revision.');
122
+ }
123
+ const inputOwner = data?.companyID;
124
+ if ((record.operation === 'create' || (data !== undefined && Object.hasOwn(data, 'companyID'))) && !isDocumentOwner(inputOwner)) {
125
+ return reason('INPUT_INVALID', 'companyID must be a non-negative signed 32-bit JSON integer.', 'data.companyID');
126
+ }
127
+ if ((record.operation === 'create' || (data !== undefined && Object.hasOwn(data, parent.field))) && data?.[parent.field] !== parentId) {
128
+ return reason('INPUT_INVALID', `${parent.field} must be the numeric parentId of the selected route.`, `data.${parent.field}`);
129
+ }
130
+ const companyIds = [...new Set([currentOwner, inputOwner].filter(isDocumentOwner))].sort((a, b) => a - b);
131
+ const scope = ctx.write?.runScope;
132
+ if (scope === undefined || ('companyIds' in scope && companyIds.some(owner => !scope.companyIds.includes(owner)))) {
133
+ return reason('TARGET_NOT_IN_SCOPE', 'The document owner company is outside the effective write scope.');
134
+ }
135
+ if ((await read(`${parent.resource}.get`, [parentId]))?.id !== parentId) {
136
+ return reason('TARGET_NOT_IN_SCOPE', 'The selected document category could not be verified.');
137
+ }
138
+ for (const owner of companyIds) {
139
+ if ((await read('companies.get', [owner]))?.id !== owner) {
140
+ return reason('TARGET_NOT_IN_SCOPE', 'The document owner company could not be verified.');
141
+ }
142
+ }
143
+ const duplicateIds = [];
144
+ if (record.operation === 'create' && duplicateFields !== undefined && data !== undefined) {
145
+ const missing = duplicateFields.find(field => ci(data, field) == null);
146
+ if (missing !== undefined)
147
+ return reason('INPUT_MISSING', `AUTOTASK_DEDUP needs data.${missing}`, `data.${missing}`);
148
+ const filter = [
149
+ ...duplicateFields.flatMap(field => duplicateFilter(field, ci(data, field))),
150
+ { field: parent.field, op: 'eq', value: parentId },
151
+ { field: 'companyID', op: 'eq', value: inputOwner },
152
+ ];
153
+ const query = await read('documents.query', [{ filter, limit: 1, names: false }]);
154
+ const items = query?.items;
155
+ const first = Array.isArray(items) ? items[0] : null;
156
+ const match = documentId(first?.id);
157
+ if (match !== undefined && first?.companyID === inputOwner && first?.[parent.field] === parentId) {
158
+ duplicateIds.push(match);
159
+ }
160
+ else if (!Array.isArray(items) || items.length !== 0 || query?.hasMore !== false || query.truncated === true) {
161
+ throw new AutotaskError('The Documents duplicate search did not establish a complete empty result. Retry the preflight before sending a write.', {
162
+ code: 'UPSTREAM_ERROR', category: 'server', operation: 'documents.query', retryable: true,
163
+ });
164
+ }
165
+ }
166
+ return {
167
+ companyIds, unresolved: [], duplicates: duplicateIds.length,
168
+ ...(current === null ? {} : { current }),
169
+ ...(isDocumentOwner(currentOwner) && documentRevision(revision) ? { expectedDocumentOwnerID: currentOwner, lastModifiedDate: revision } : {}),
170
+ inputs: { reads: { parentId, companyIds, ...(id === undefined ? {} : { id, currentOwner, revision }) }, duplicateIds },
171
+ };
172
+ }
89
173
  function categoryParentId(value) {
90
174
  return typeof value === 'number' && Number.isInteger(value) && value >= 0 && value <= 2_147_483_647;
91
175
  }
@@ -530,6 +614,8 @@ export async function takeCallSnapshot(ctx, record, parsed, signal) {
530
614
  };
531
615
  }
532
616
  export async function takeSnapshot(ctx, record, parsed, duplicateFields, signal, matchesApproval) {
617
+ if (record.resource === 'documents')
618
+ return takeDocumentSnapshot(ctx, record, parsed, duplicateFields, signal);
533
619
  if (writeShape(record) === 'call')
534
620
  return takeCallSnapshot(ctx, record, parsed, signal);
535
621
  // parentId 0 names a record only under a company parent (company 0): any other is refused before any read
@@ -577,7 +663,7 @@ export async function takeSnapshot(ctx, record, parsed, duplicateFields, signal,
577
663
  const references = async () => {
578
664
  let current;
579
665
  let lastModifiedDate;
580
- if (targets.id !== undefined) {
666
+ if (typeof targets.id === 'number') {
581
667
  if (targets.toId !== undefined && !hasSimpleGet(record.resource, ctx)) {
582
668
  // a move's source whose get is parent-scoped (a ticket charge): read it by id, as the SDK does; its ticketID anchors it
583
669
  const key = `${record.resource}:${targets.id}`;
@@ -5,7 +5,7 @@ import type { Counters, WriteFacts } from '../evaluate.js';
5
5
  export interface PlanTargets {
6
6
  resource: string;
7
7
  parentId?: number;
8
- id?: number;
8
+ id?: number | string;
9
9
  /** A move (issue #107): the target ticket; `id` is the source record. */
10
10
  toId?: number;
11
11
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "iit-mcp-autotask",
3
- "version": "0.65.0",
3
+ "version": "0.65.1",
4
4
  "description": "MCP server for the Autotask (Datto) PSA domain, built on the node-autotask SDK",
5
5
  "license": "MIT",
6
6
  "author": "Max Soukhomlinov",
@@ -54,7 +54,7 @@
54
54
  },
55
55
  "dependencies": {
56
56
  "@modelcontextprotocol/server": "^2.2.0",
57
- "node-autotask": "0.94.2",
57
+ "node-autotask": "0.95.0",
58
58
  "zod": "^4.6.7"
59
59
  },
60
60
  "devDependencies": {
package/server.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "iit-mcp-autotask",
3
- "version": "0.65.0",
3
+ "version": "0.65.1",
4
4
  "description": "MCP server for the Autotask (Datto) PSA API, powered by the node-autotask SDK",
5
5
  "mcpProtocolBaseline": "2026-07-28",
6
6
  "legacyProtocolFallback": "2025-11-25",
@@ -62,7 +62,7 @@
62
62
  "capabilitiesManifest": "capabilities.json",
63
63
  "sdk": {
64
64
  "package": "node-autotask",
65
- "versionRange": "0.94.2"
65
+ "versionRange": "0.95.0"
66
66
  },
67
67
  "vendorExtensions": false,
68
68
  "credentialModelNote": "per-request; server-held under stdio or, on HTTP, only behind AUTOTASK_HTTP_AUTH=tokens; operator plans and the ledger are keyed by principal and tenant id, never by credential, and an apply authenticates the request credential and restores the plan's per-write impersonation"
@@ -5,7 +5,7 @@ version: 1
5
5
  profile: readonly
6
6
  description: Filter footguns for autotask_query: strict date lt, case-insensitive contains, FK 0 vs NULL, field-name checks, all-strings values.
7
7
  when_not_to_use: the filter grammar itself (the 13 operators + and/or grouping, server instructions); the per-operation notes (autotask_describe)
8
- ops: ["autotask_query:tickets.query", "autotask_query:time_entries.query", "autotask_query:service_calls.query", "autotask_query:contracts.query", "autotask_query:time_off_requests.query", "autotask_read:operations.fieldCatalog", "autotask_resource_workload", "autotask_query:operations.aggregate", "autotask_query:organizational_resources.query", "autotask_query:resource_daily_availabilities.query", "autotask_read:organizational_resources.listByParent", "autotask_read:resource_daily_availabilities.listByParent"]
8
+ ops: ["autotask_query:tickets.query", "autotask_query:time_entries.query", "autotask_query:service_calls.query", "autotask_query:contracts.query", "autotask_query:time_off_requests.query", "autotask_read:operations.fieldCatalog", "autotask_resource_workload", "autotask_query:operations.aggregate", "autotask_query:organizational_resources.query", "autotask_query:resource_daily_availabilities.query", "autotask_read:organizational_resources.listByParent", "autotask_read:resource_daily_availabilities.listByParent", "autotask_query:documents.query"]
9
9
  inputs: {"type": "object", "required": [], "properties": {}}
10
10
  outcomes: ["ok", "error"]
11
11
  hazards: ["gt/lt around a day boundary silently drops an edge day", "ticketID eq 0 finds nothing (time_entries store NULL)", "an unknown field name is a zero-query-wire CONFIG_ERROR (0.20.0 pre-validation; a cold field cache makes one vendor metadata GET first)"]
@@ -34,6 +34,8 @@ No inputs: this is a reference page about the filter behaviour of autotask_query
34
34
 
35
35
  Filter `organizational_resources` on `organizationalLevelAssociationID` and `resource_daily_availabilities` on `resourceID`. Use `autotask_read` with `organizational_resources.listByParent` or `resource_daily_availabilities.listByParent` and `[parentId]` for one native page with `hasMore` and no cursor. Native and global visibility may differ. An empty response is inconclusive. Neither parent establishes company ownership.
36
36
 
37
+ For Documents, filter by `companyID` or `documentCategoryID`. The server verifies owner scope.
38
+
37
39
  ## Guardrails
38
40
 
39
41
  - Apply the 8 rules when composing or debugging any autotask_query filter.
@@ -78,4 +80,5 @@ Filter `organizational_resources` on `organizationalLevelAssociationID` and `res
78
80
  | autotask_query | resource_daily_availabilities.query | read | - |
79
81
  | autotask_read | organizational_resources.listByParent | read | parentId |
80
82
  | autotask_read | resource_daily_availabilities.listByParent | read | parentId |
83
+ | autotask_query | documents.query | read | - |
81
84
  <!-- generated:end -->