iit-mcp-autotask 0.65.0 → 0.66.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/.env.example +1 -0
  2. package/README.md +31 -4
  3. package/capabilities.json +2 -2
  4. package/dist/policy.d.ts +1 -0
  5. package/dist/policy.js +9 -0
  6. package/dist/tools/aggregate.js +4 -1
  7. package/dist/tools/billing-review-projection.js +1 -1
  8. package/dist/tools/catalog-data.d.ts +2 -2
  9. package/dist/tools/catalog-data.js +4 -4
  10. package/dist/tools/composites.js +11 -8
  11. package/dist/tools/context/client.js +2 -2
  12. package/dist/tools/context/derive.js +8 -5
  13. package/dist/tools/context/types.d.ts +4 -0
  14. package/dist/tools/dispatch.js +15 -1
  15. package/dist/tools/documents.d.ts +11 -0
  16. package/dist/tools/documents.js +133 -0
  17. package/dist/tools/lists.js +18 -5
  18. package/dist/tools/meta.js +34 -9
  19. package/dist/tools/resolves.d.ts +5 -1
  20. package/dist/tools/resolves.js +45 -14
  21. package/dist/tools/results/errors.js +15 -12
  22. package/dist/tools/results/untrusted.js +7 -1
  23. package/dist/tools/schemas.d.ts +11 -0
  24. package/dist/tools/schemas.js +10 -1
  25. package/dist/tools/server.js +4 -1
  26. package/dist/tools/write/apply.js +91 -23
  27. package/dist/tools/write/guard-facts.d.ts +19 -0
  28. package/dist/tools/write/guard-facts.js +168 -0
  29. package/dist/tools/write/impersonation.js +1 -1
  30. package/dist/tools/write/outcome.js +8 -1
  31. package/dist/tools/write/parse.js +14 -0
  32. package/dist/tools/write/preview.js +29 -11
  33. package/dist/tools/write/sdk-approval.d.ts +25 -0
  34. package/dist/tools/write/sdk-approval.js +97 -0
  35. package/dist/tools/write/snapshot.d.ts +3 -1
  36. package/dist/tools/write/snapshot.js +100 -8
  37. package/dist/write/store/types.d.ts +3 -1
  38. package/package.json +2 -2
  39. package/server.json +2 -2
  40. package/skills/filter-semantics.md +4 -1
  41. package/skills/slim-reads.md +1 -1
package/.env.example CHANGED
@@ -57,6 +57,7 @@ AUTOTASK_PROFILE=readonly
57
57
  # unattended or deny (this server asks the person). HTTP: allow or deny only (the MCP client gates).
58
58
  # Grammar, hard rules and dedup: docs/write-gate.md.
59
59
  # AUTOTASK_WRITE=*:deny,tickets.*:allow,time_entries.create:allow,companies.update:deny
60
+ # Any guarded SDK family is served by listing it (for example company_to_dos.*:allow); the account-wide roots also need an all-company run scope.
60
61
  # AUTOTASK_DEDUP=companies.create:companyName
61
62
  # operator: the state dir (mode 0700; plans, ledger, audit, locks; same-version processes on one host may share it).
62
63
  # AUTOTASK_STATE_DIR=/var/lib/autotask-mcp
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
@@ -309,10 +315,31 @@ signal. Keep the rest of the state dir; `audit.jsonl` is the write history.
309
315
 
310
316
  ### Query results: TSV, `output_path` and the saved-file shape
311
317
 
312
- Name and label siblings are enabled by default on SDK-backed reads and the four SDK composites.
313
- A supported per-call `names: false` disables them; composite `max_name_reads` still lowers the SDK name-read budget.
314
-
315
- `autotask_query` always wraps untrusted text and uses the SDK's default transport and labels; `via`, `names`, and `untrusted_wrapper` are refused as unknown inputs.
318
+ Name and label siblings (`<field>Label`, `<id>Name`) are on by default on every read whose SDK operation supports them
319
+ (node-autotask `docs/LABEL-COVERAGE.md` is the coverage inventory). `names: false` is the per-call opt-out and returns raw
320
+ values with no label-only reads; it is a top-level input of:
321
+
322
+ - `autotask_query`: rows, `tsv`, `group_by` keys and `output_path` (a `names` key inside a `*.query` or
323
+ `operations.aggregate` bag sent through `autotask_read` wins over the call's option);
324
+ - `autotask_read`: every read of the call, a single operation or a batch of `items` (`*.get`, `*.resolve`, searches, finders,
325
+ `operations.fetchByIds`, `operations.resolveAny`, `operations.searchAcrossResources`, queries, aggregates);
326
+ - `autotask_resolve`: every branch (exact, contains, fuzzy where it applies, sweep, staff, natural key);
327
+ - the composites `autotask_ticket_full_context`, `autotask_company_full_profile`, `autotask_contact_full_profile`,
328
+ `autotask_contract_full_profile`, `autotask_service_call_full_profile`, `autotask_project_get_context`,
329
+ `autotask_configuration_item_profile`, `autotask_quote_get`, `autotask_resource_workload` and `autotask_invoice_get`
330
+ (record format). `max_name_reads` lowers the name-read budget of the composites whose SDK option bag takes it
331
+ (ticket, company, project, configuration item).
332
+
333
+ `names: true` on an operation that has no label path (counts, metadata, downloads, the invoice exports) is refused by the SDK
334
+ before any request; `names: false` is always a no-op there. Genuinely unsupported (SDK basis, `docs/LABEL-COVERAGE.md`):
335
+ counts and metadata reads, file and export payloads, integration-endpoint results, `companies.searchFuzzy` (a fixed
336
+ four-field projection), and the purpose-built roll-ups (revenue, AR aging, WIP, margin, recurring revenue, non-chargeable
337
+ work), which carry their own pinned label fields. A picklist `*Label` sibling is absent when the tenant's API user cannot read
338
+ the field metadata (the raw value stays); an id with no readable name gets a `null` `*Name`. Both are visibility limits, never
339
+ proof of absence. The server's own snapshot, guard and verification reads (write previews, apply read-backs, the verification
340
+ projections) always send `names: false`, so approved plans and strict outputs stay raw.
341
+
342
+ `autotask_query` always wraps untrusted text and uses the SDK's default transport; `via` and `untrusted_wrapper` are refused as unknown inputs.
316
343
 
317
344
  `autotask_query` answers `data.result` with the SDK's bounded-query envelope:
318
345
 
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 2,082 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": 2082,
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;
@@ -153,7 +153,7 @@ export async function readBillingReview(ctx, input, signal) {
153
153
  else
154
154
  invalid();
155
155
  // SDK queries are uncached; its fresh option is valid only for primitive get reads.
156
- const result = await readOneItem(ctx, input.operation, args, signal, input.operation === 'time_entries.get' ? { fresh: true } : undefined, project);
156
+ const result = await readOneItem(ctx, input.operation, args, signal, input.operation === 'time_entries.get' ? { fresh: true, names: false } : { names: false }, project); // SDK queries are uncached, so no fresh; labels are never wanted in a verification snapshot
157
157
  if (result.aborted)
158
158
  return abortedAnswer(ctx.correlationId);
159
159
  if (result.scopeNote !== undefined)
@@ -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 = "87f8f8c5b88bdca0067c5a6fc7bcbb854f16a3f0b5bdd23aff0c27d033b37809";
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 = '87f8f8c5b88bdca0067c5a6fc7bcbb854f16a3f0b5bdd23aff0c27d033b37809';
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).
@@ -18,7 +18,7 @@
18
18
  */
19
19
  import { AutotaskConfigError } from 'node-autotask';
20
20
  import { TICKET_FULL_CONTEXT_INPUT, COMPANY_FULL_PROFILE_INPUT, COMPANY_PROFILE_PART_LIMIT_DEFAULT, CONFIGURATION_ITEM_PROFILE_INPUT, PROJECT_GET_CONTEXT_INPUT, QUOTE_GET_INPUT, INVOICE_GET_INPUT, CONTACT_FULL_PROFILE_INPUT, SERVICE_CALL_FULL_PROFILE_INPUT, CONTRACT_FULL_PROFILE_INPUT, RESOURCE_WORKLOAD_INPUT, closedInput, } from './schemas.js';
21
- import { abortedAnswer } from './dispatch.js';
21
+ import { abortedAnswer, InputInvalidError } from './dispatch.js';
22
22
  import { crossResourceUntrusted, documentCore, markFilePayload, markResult } from './results/untrusted.js';
23
23
  import { ok } from './results/envelope.js';
24
24
  import { resolveOutputTarget } from './output-file.js';
@@ -184,7 +184,7 @@ export function buildProjectGetContext(ctx) {
184
184
  opts: (a) => bagOf([['names', a.names], ['maxNameReads', a.max_name_reads]]),
185
185
  extraParts: async (a, signal) => {
186
186
  const [phases, tasks] = await Promise.all([
187
- projectRowsPart(ctx, 'phases', a.id, { limit: PROJECT_PHASE_CAP, includeFields: PHASE_FIELDS }, signal),
187
+ projectRowsPart(ctx, 'phases', a.id, { limit: PROJECT_PHASE_CAP, includeFields: PHASE_FIELDS, names: a.names }, signal),
188
188
  projectRowsPart(ctx, 'tasks', a.id, { limit: PROJECT_TASK_CAP, includeFields: TASK_FIELDS, names: a.names }, signal),
189
189
  ]);
190
190
  return phases === undefined || tasks === undefined ? undefined : { phases, tasks };
@@ -197,7 +197,7 @@ export function buildQuoteGet(ctx) {
197
197
  operation: 'quotes.withItems',
198
198
  title: 'Get a quote with its line items',
199
199
  input: closedInput(QUOTE_GET_INPUT),
200
- opts: (a) => bagOf([['itemLimit', a.item_limit]]),
200
+ opts: (a) => bagOf([['itemLimit', a.item_limit], ['names', a.names]]),
201
201
  });
202
202
  }
203
203
  // ---- autotask_invoice_get: the invoice record (A1: there is no invoice_items resource) ----
@@ -223,6 +223,8 @@ export function buildInvoiceGet(ctx) {
223
223
  run: async (raw, signal) => {
224
224
  const args = raw;
225
225
  const op = OPS[args.format];
226
+ if (args.names === true && args.format !== 'record')
227
+ throw new InputInvalidError('invoice: names applies to the record format only (the exports carry no labels)', 'names');
226
228
  assertOperationPermitted(op, ctx.record(op), ctx.config, ctx.log);
227
229
  if (args.format === 'record' && args.output_path !== undefined) {
228
230
  throw new AutotaskConfigError('output_path applies to the export formats (html, xml, pdf): the record is a small JSON payload, always served in-band (nothing was dialled, nothing was written)', { operation: op });
@@ -237,7 +239,8 @@ export function buildInvoiceGet(ctx) {
237
239
  relativePath: args.output_path,
238
240
  })
239
241
  : undefined;
240
- const result = await ctx.ops.invokeRead(ctx.client, op, [args.id], undefined, signal);
242
+ // #502: names rides the record read only; the export formats carry no labels (names:true there is refused by the SDK)
243
+ const result = await ctx.ops.invokeRead(ctx.client, op, [args.id], args.names === undefined ? undefined : { names: args.names }, signal);
241
244
  if (result === undefined)
242
245
  return abortedAnswer(ctx.correlationId);
243
246
  if (args.format === 'record') {
@@ -277,7 +280,7 @@ export function buildContactFullProfile(ctx) {
277
280
  operation: 'contacts.fullProfile',
278
281
  title: 'Get a contact with its company and open tickets',
279
282
  input: closedInput(CONTACT_FULL_PROFILE_INPUT),
280
- opts: (a) => bagOf([['ticketLimit', a.ticket_limit]]),
283
+ opts: (a) => bagOf([['ticketLimit', a.ticket_limit], ['names', a.names]]),
281
284
  });
282
285
  }
283
286
  // ---- autotask_service_call_full_profile: the call, its tickets, its tasks, its resource assignments ----
@@ -286,7 +289,7 @@ export function buildServiceCallFullProfile(ctx) {
286
289
  operation: 'service_calls.fullProfile',
287
290
  title: 'Get a service call with its tickets, tasks and resource assignments',
288
291
  input: closedInput(SERVICE_CALL_FULL_PROFILE_INPUT),
289
- opts: (a) => bagOf([['ticketLimit', a.ticket_limit], ['taskLimit', a.task_limit]]),
292
+ opts: (a) => bagOf([['ticketLimit', a.ticket_limit], ['taskLimit', a.task_limit], ['names', a.names]]),
290
293
  });
291
294
  }
292
295
  // ---- autotask_contract_full_profile: the contract, its services, its billing rules,
@@ -296,7 +299,7 @@ export function buildContractFullProfile(ctx) {
296
299
  operation: 'contracts.fullProfile',
297
300
  title: 'Get a contract with its services, billing rules, recent charges and service units',
298
301
  input: closedInput(CONTRACT_FULL_PROFILE_INPUT),
299
- opts: (a) => bagOf([['serviceLimit', a.service_limit], ['billingRuleLimit', a.billing_rule_limit]]),
302
+ opts: (a) => bagOf([['serviceLimit', a.service_limit], ['billingRuleLimit', a.billing_rule_limit], ['names', a.names]]),
300
303
  });
301
304
  }
302
305
  // ---- autotask_resource_workload: the resource, its open work, its balances ----
@@ -305,7 +308,7 @@ export function buildResourceWorkload(ctx) {
305
308
  operation: 'resources.workload',
306
309
  title: 'Get a resource\'s workload: open tickets, assignments, balances, time off',
307
310
  input: closedInput(RESOURCE_WORKLOAD_INPUT),
308
- opts: (a) => bagOf([['ticketLimit', a.ticket_limit], ['taskLimit', a.task_limit], ['timeOffLimit', a.time_off_limit]]),
311
+ opts: (a) => bagOf([['ticketLimit', a.ticket_limit], ['taskLimit', a.task_limit], ['timeOffLimit', a.time_off_limit], ['names', a.names]]),
309
312
  });
310
313
  }
311
314
  //# sourceMappingURL=composites.js.map
@@ -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) {
@@ -63,10 +63,12 @@ export interface ToolOps {
63
63
  resources?: readonly string[];
64
64
  match?: 'exact' | 'auto';
65
65
  limit?: number;
66
+ names?: boolean;
66
67
  }, signal?: AbortSignal): Promise<unknown>;
67
68
  searchAcrossResources(client: ToolClient, query: string, opts?: {
68
69
  resources?: readonly string[];
69
70
  limit?: number;
71
+ names?: boolean;
70
72
  }, signal?: AbortSignal): Promise<unknown>;
71
73
  /** Zero wire by construction — no signal needed. */
72
74
  relationshipMap(client: ToolClient, resourceKey: string): Promise<unknown>;
@@ -108,6 +110,8 @@ export interface ToolDeps {
108
110
  * principal (the token's, or `AUTOTASK_PRINCIPAL` on stdio) and its run scope. Absent on readonly.
109
111
  */
110
112
  write?: WriteDeps;
113
+ /** Effective token scope, when present on a read-only request. */
114
+ runScope?: RunScope;
111
115
  /** The client capabilities the connection's `initialize` declared (2025-era only; absent on a stateless request). */
112
116
  clientCapabilities?: () => ClientCapabilities | undefined;
113
117
  }
@@ -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';
@@ -77,7 +78,7 @@ export function buildQuery(ctx) {
77
78
  const clash = ['latest', 'include_fields', 'note_chars', 'format', 'output_path', 'acknowledge_unscoped'].find((k) => args[k] !== undefined);
78
79
  if (clash !== undefined)
79
80
  throw new InputInvalidError(`query: ${clash} lists rows; group_by, sum and count return totals only (pass filter, top and limit)`, clash);
80
- return runAggregate(ctx, operation, args.filter, { groupBy: args.group_by, sum: args.sum, top: args.top, limit: args.limit }, signal, { resource: args.resource });
81
+ return runAggregate(ctx, operation, args.filter, { groupBy: args.group_by, sum: args.sum, top: args.top, limit: args.limit, names: args.names }, signal, { resource: args.resource });
81
82
  }
82
83
  if (args.top !== undefined)
83
84
  throw new InputInvalidError('query: top caps the groups of group_by / sum', 'top');
@@ -103,10 +104,17 @@ 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
+ if (args.names !== undefined)
108
+ bag.names = args.names;
109
+ const companies = args.resource === 'documents' ? documentCompanyScope(ctx) : undefined;
110
+ const rawResult = await ctx.ops.invokeRead(ctx.client, operation, [scopedDocumentQuery(operation, bag, companies)], undefined, signal)
107
111
  .catch((err) => { throw fieldNameInput(scopeRequiredInput(err, 'filter', true), true); });
108
- if (result === undefined)
112
+ if (rawResult === undefined)
109
113
  return abortedAnswer(ctx.correlationId);
114
+ const page = rawResult;
115
+ if (companies !== undefined)
116
+ verifyDocumentRows(operation, page.items, companies);
117
+ const result = companies === undefined ? rawResult : { ...page, items: projectDocumentRows(page.items, includeFields) };
110
118
  const v = result;
111
119
  const n = v.count ?? v.total ?? (Array.isArray(v.items) ? v.items.length : undefined);
112
120
  const capped = result.noteCharsTruncated;
@@ -217,15 +225,20 @@ async function outputPathAnswer(ctx, resource, operation, noun, fields, args, si
217
225
  relativePath: args.output_path,
218
226
  });
219
227
  const asTsv = args.format === 'tsv';
228
+ const companies = resource === 'documents' ? documentCompanyScope(ctx) : undefined;
220
229
  const exported = await exportQueryFile({
221
230
  target, fields, format: asTsv ? 'tsv' : 'json', signal,
222
- readPages: consume => ctx.ops.invokeReadPages(ctx.client, operation, [{
231
+ readPages: consume => ctx.ops.invokeReadPages(ctx.client, operation, [scopedDocumentQuery(operation, {
223
232
  filter: args.filter,
224
233
  limit: 500,
225
234
  walk: { maxRows: OUTPUT_MAX_ROWS },
226
235
  ...(args.include_fields === undefined ? {} : { includeFields: args.include_fields }),
227
236
  ...(args.acknowledge_unscoped === undefined ? {} : { acknowledgeUnscoped: args.acknowledge_unscoped }),
228
- }], consume, undefined, signal).catch((err) => { throw fieldNameInput(scopeRequiredInput(err, 'filter', true), true); }),
237
+ ...(args.names === undefined ? {} : { names: args.names }),
238
+ }, companies)], companies === undefined ? consume : page => {
239
+ verifyDocumentRows(operation, page.items, companies);
240
+ return consume({ ...page, items: projectDocumentRows(page.items, args.include_fields) });
241
+ }, undefined, signal).catch((err) => { throw fieldNameInput(scopeRequiredInput(err, 'filter', true), true); }),
229
242
  }).catch((error) => { if (error instanceof QueryExportIncompleteError)
230
243
  return undefined; throw error; });
231
244
  if (exported === undefined)