iit-mcp-autotask 0.64.2 → 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,435 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": 1435,
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;
@@ -71,12 +71,13 @@ export declare function staffReadParentFilter(resource: string): string | undefi
71
71
  export declare function isStaffReadOperation(operation: unknown): operation is string;
72
72
  /** Exact registered metadata reads can settle on a shared wire request. */
73
73
  export declare function isRegisteredMetadataRead(operation: unknown): operation is string;
74
- /** Match only a trusted upstream HTTP 403 on a registered staff read. */
75
- export declare function isStaffReadPermissionRefusal(error: {
74
+ /** A direct HTTP 403 on these reads can be an entity permission refusal. */
75
+ export declare function isEntityReadPermissionRefusal(error: {
76
76
  operation?: unknown;
77
77
  httpStatus?: unknown;
78
78
  category?: unknown;
79
79
  }): boolean;
80
+ export declare function isDocumentReadOperation(operation: unknown): boolean;
80
81
  /** The served tool for this row's operation in a deployment serving `served`, or `null`. */
81
82
  export declare function servedToolName(row: CatalogRow, served: ReadonlySet<string>): string | null;
82
83
  /** The registry keys projected onto an MCP tool name (the reverse of {@link TOOL_NAME_BY_OP}); empty when none. */
@@ -121,7 +122,7 @@ export declare function sdkCacheOptions(cache: 'on' | 'off'): Pick<AutotaskConfi
121
122
  * fails the boot (or the CI test) instead of quietly shipping a tool surface that no longer
122
123
  * describes the SDK behind it.
123
124
  */
124
- export declare const BUILT_AGAINST_PLAN_HASH = "51888554f455b96e13c50591342fa516b095065762430b783201ac7a995a0901";
125
+ export declare const BUILT_AGAINST_PLAN_HASH = "851551c93be98a8eb27a8acf3d7c0e895e3024097150a86f5f9eed6229b1bd32";
125
126
  /**
126
127
  * Fail fast when the installed SDK's plan has moved out from under this surface.
127
128
  * Called at boot (main.ts) and safe to call repeatedly (pure comparison).
@@ -121,9 +121,14 @@ export function isRegisteredMetadataRead(operation) {
121
121
  const record = typeof operation === 'string' ? recordById(operation) : undefined;
122
122
  return record?.effect === 'read' && /^(getEntityInfo|getFieldInfo|getUdfInfo)$/.test(record.operation);
123
123
  }
124
- /** Match only a trusted upstream HTTP 403 on a registered staff read. */
125
- export function isStaffReadPermissionRefusal(error) {
126
- return error.httpStatus === 403 && error.category === 'auth' && isStaffReadOperation(error.operation);
124
+ /** A direct HTTP 403 on these reads can be an entity permission refusal. */
125
+ export function isEntityReadPermissionRefusal(error) {
126
+ return error.httpStatus === 403 && error.category === 'auth'
127
+ && (isStaffReadOperation(error.operation) || isDocumentReadOperation(error.operation));
128
+ }
129
+ export function isDocumentReadOperation(operation) {
130
+ const record = typeof operation === 'string' ? recordById(operation) : undefined;
131
+ return record?.effect === 'read' && (record.resource === 'document_categories' || record.resource === 'documents');
127
132
  }
128
133
  /** The served tool for this row's operation in a deployment serving `served`, or `null`. */
129
134
  export function servedToolName(row, served) {
@@ -222,7 +227,7 @@ export function sdkCacheOptions(cache) {
222
227
  * fails the boot (or the CI test) instead of quietly shipping a tool surface that no longer
223
228
  * describes the SDK behind it.
224
229
  */
225
- export const BUILT_AGAINST_PLAN_HASH = '51888554f455b96e13c50591342fa516b095065762430b783201ac7a995a0901';
230
+ export const BUILT_AGAINST_PLAN_HASH = '851551c93be98a8eb27a8acf3d7c0e895e3024097150a86f5f9eed6229b1bd32';
226
231
  /**
227
232
  * Fail fast when the installed SDK's plan has moved out from under this surface.
228
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 { 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
@@ -15,7 +15,7 @@ export const PLACEHOLDER_BASE_URL = `${PLACEHOLDER_ORIGIN}/atservicesrest`;
15
15
  /** Sentinel credential values a placeholder client is constructed with (never real, never dialled). */
16
16
  export const SENTINEL_CREDENTIAL = 'unresolved-request-scope';
17
17
  // SDK classifications here are fixed tokens. A vendor-origin SDK code must contain a digit.
18
- const METADATA_AUDIT_CODES = new Set([
18
+ const READ_AUDIT_CODES = new Set([
19
19
  'ABORTED', 'HOST_POLICY_DENIED', 'MAINTENANCE', 'REDIRECT_BLOCKED', 'RESPONSE_REJECTED', 'RESPONSE_TOO_LARGE',
20
20
  'RATE_LIMITED', 'RATE_LIMITED_COOLDOWN', 'CIRCUIT_BREAKER_OPEN',
21
21
  'TIMEOUT', 'NETWORK_ERROR', 'INVALID_RESPONSE', 'UNEXPECTED_CONTENT_TYPE', 'EMPTY_RESPONSE',
@@ -23,9 +23,9 @@ const METADATA_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)) {
26
+ if (isRegisteredMetadataRead(operation) || isDocumentReadOperation(operation)) {
27
27
  // A terminal SDK failure can carry the status from an earlier retry.
28
- if (METADATA_AUDIT_CODES.has(code))
28
+ if (READ_AUDIT_CODES.has(code))
29
29
  return code;
30
30
  return status !== undefined && status >= 300 ? errorFromStatus(status, undefined).code : 'UPSTREAM_ERROR';
31
31
  }
@@ -139,7 +139,13 @@ export function buildStdioClient(config, log) {
139
139
  * `invokeRead` and its governor; `authenticate.*` is refused by the deployment policy before it.)
140
140
  */
141
141
  export const defaultToolOps = {
142
- invokeRead: (client, operation, args, opts, signal) => withSignal(client, signal, () => invokeRead(client, operation, args, opts ?? {})),
142
+ invokeRead: (client, operation, args, { freshMetadata, ...opts } = {}, signal) => withSignal(client, signal, () => {
143
+ const sdk = client;
144
+ // The SDK documents invalidation as the way to refresh a raw, no-argument metadata read.
145
+ if (freshMetadata === true)
146
+ sdk.http.fieldCache?.invalidate(`${operation.split('.')[0]}:fields`);
147
+ return invokeRead(sdk, operation, args, opts);
148
+ }),
143
149
  invokeReadPages: (client, operation, args, onPage, opts, signal) => withSignal(client, signal, () => invokeReadPages(client, operation, args, onPage, opts ?? {})),
144
150
  invokeWrite: (client, operation, args, opts, signal) => withSignal(client, signal, () => invokeWrite(client, operation, args, opts ?? {})),
145
151
  invokeDelete: (client, operation, args, opts, signal) => withSignal(client, signal, () => invokeDelete(client, operation, args, opts ?? {})),
@@ -1,13 +1,17 @@
1
- /** Deriving a tool context from the deps, and releasing a client on error (issue #91). */
2
- import { AutotaskClient, type AutotaskConfig } from 'node-autotask';
1
+ import { AutotaskClient, type AutotaskConfig, type AutotaskError } from 'node-autotask';
3
2
  import type { ClientPool } from 'node-autotask/pool';
4
3
  import type { Logger } from '../../logger.js';
5
4
  import type { ToolDeps, ToolContext } from './types.js';
5
+ export declare function isImpersonationValidationDenial(error: unknown): error is AutotaskError & {
6
+ httpStatus: 401 | 403;
7
+ };
8
+ /** Scope the wire hook to the validation call, since resources.get also serves ordinary reads. */
9
+ export declare function withImpersonationValidation<T>(ctx: ToolContext, read: () => Promise<T>): Promise<T>;
6
10
  /** Resolve the SDK client and bind invalidation to its exact pool key. */
7
11
  export declare function getPooledClient(pool: ClientPool, config: AutotaskConfig, log: Logger): AutotaskClient;
8
12
  /** Derive the context the registrations share. */
9
13
  export declare function deriveToolContext(deps: ToolDeps, served?: ReadonlySet<string>): ToolContext;
10
- /** Only a resolved direct identity can treat a staff 403 as an entity permission refusal. */
14
+ /** An entity permission refusal applies only to a resolved direct identity. */
11
15
  export declare function isDirectIdentity(deps: Pick<ToolDeps, 'poolConfig'>): boolean;
12
16
  /**
13
17
  * A vendor 401 (or impersonation-scope 401/403) deletes the pooled entry so a stale identity is
@@ -1,12 +1,23 @@
1
1
  /** Deriving a tool context from the deps, and releasing a client on error (issue #91). */
2
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
3
  import { AutotaskClient, isAutotaskError } from 'node-autotask';
3
4
  import { isAuthFailure } from '../results/errors.js';
4
- import { isRegisteredMetadataRead, isStaffReadOperation, recordById, toolDescription, untrustedFieldsOf } from '../catalog-data.js';
5
+ import { isDocumentReadOperation, isRegisteredMetadataRead, isStaffReadOperation, recordById, toolDescription, untrustedFieldsOf } from '../catalog-data.js';
5
6
  // A real client with this hook handles eviction once per wire refusal, even if multiple readers share the result.
6
7
  const auditInvalidatesCredentialReads = new WeakSet();
8
+ const impersonationValidation = new AsyncLocalStorage();
9
+ const invalidatedValidationErrors = new WeakSet();
7
10
  function isCredentialReadDenial(operation, status, impersonated) {
8
11
  return (status === 401 || (status === 403 && impersonated)) &&
9
- (isStaffReadOperation(operation) || isRegisteredMetadataRead(operation));
12
+ (isStaffReadOperation(operation) || isRegisteredMetadataRead(operation) || isDocumentReadOperation(operation));
13
+ }
14
+ function isGuardedDocumentMutation(operation, method) {
15
+ return (operation === 'document_categories.create' && method === 'POST')
16
+ || (operation === 'document_categories.update' && method === 'PUT')
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');
10
21
  }
11
22
  function invalidateCredentialReads(pool, config, client, log) {
12
23
  // A pinned stdio or in-flight client can outlive its pool entry. Clear its stores if the pool did not.
@@ -22,19 +33,52 @@ function invalidateCredentialReads(pool, config, client, log) {
22
33
  if (removed)
23
34
  log.info('deleted pooled client after credential refusal', { removed, poolSize: pool.size });
24
35
  }
36
+ export function isImpersonationValidationDenial(error) {
37
+ return isAutotaskError(error) && error.operation === 'resources.get' && error.category === 'auth'
38
+ && (error.httpStatus === 401 || error.httpStatus === 403);
39
+ }
40
+ /** Scope the wire hook to the validation call, since resources.get also serves ordinary reads. */
41
+ export async function withImpersonationValidation(ctx, read) {
42
+ const scope = { client: ctx.client, invalidated: false };
43
+ try {
44
+ return await impersonationValidation.run(scope, read);
45
+ }
46
+ catch (error) {
47
+ const { pool, poolConfig, client, log } = ctx;
48
+ if (pool !== undefined && poolConfig?.impersonationResourceId !== undefined && isImpersonationValidationDenial(error)) {
49
+ if (!scope.invalidated)
50
+ invalidateCredentialReads(pool, poolConfig, client instanceof AutotaskClient ? client : undefined, log);
51
+ invalidatedValidationErrors.add(error);
52
+ }
53
+ throw error;
54
+ }
55
+ }
25
56
  /** Resolve the SDK client and bind invalidation to its exact pool key. */
26
57
  export function getPooledClient(pool, config, log) {
27
58
  const client = pool.get({
28
59
  ...config,
29
60
  onAudit(event) {
30
- const { status, operation, errorCode, notSent } = event;
61
+ const { status, operation, method, errorCode, notSent } = event;
31
62
  // The SDK can retain a machine code containing digits for a real status error.
32
63
  // Its own abort, maintenance and response-policy codes do not describe an auth denial.
33
64
  const authCode = errorCode === (status === 401 ? 'UNAUTHORIZED' : 'FORBIDDEN') ||
34
65
  (errorCode !== undefined && /^[a-z0-9][a-z0-9_-]{2,}$/i.test(errorCode) && /\d/.test(errorCode));
35
- if (notSent !== true && authCode && isCredentialReadDenial(operation, status, config.impersonationResourceId !== undefined)) {
36
- auditInvalidatesCredentialReads.add(client);
37
- invalidateCredentialReads(pool, config, client, log);
66
+ if (notSent !== true && authCode) {
67
+ const readDenial = isCredentialReadDenial(operation, status, config.impersonationResourceId !== undefined);
68
+ if (readDenial)
69
+ auditInvalidatesCredentialReads.add(client);
70
+ const validation = impersonationValidation.getStore();
71
+ const validationDenial = validation?.client === client && config.impersonationResourceId !== undefined
72
+ && operation === 'resources.get' && method === 'GET' && (status === 401 || status === 403);
73
+ // The wire can settle after apply has returned an unknown outcome.
74
+ if (readDenial || validationDenial || (status === 401 && isGuardedDocumentMutation(operation, method))) {
75
+ invalidateCredentialReads(pool, config, client, log);
76
+ }
77
+ if (validationDenial) {
78
+ validation.invalidated = true;
79
+ config.onAudit?.({ ...event, errorCode: status === 401 ? 'UNAUTHORIZED' : 'FORBIDDEN' });
80
+ return;
81
+ }
38
82
  }
39
83
  config.onAudit?.(event);
40
84
  },
@@ -55,7 +99,7 @@ export function deriveToolContext(deps, served = new Set()) {
55
99
  description: toolDescription,
56
100
  };
57
101
  }
58
- /** Only a resolved direct identity can treat a staff 403 as an entity permission refusal. */
102
+ /** An entity permission refusal applies only to a resolved direct identity. */
59
103
  export function isDirectIdentity(deps) {
60
104
  return deps.poolConfig !== undefined && deps.poolConfig.impersonationResourceId === undefined;
61
105
  }
@@ -68,6 +112,8 @@ export function releaseClientOnError(deps, err) {
68
112
  if (deps.pool === undefined || deps.poolConfig === undefined)
69
113
  return;
70
114
  if (isAutotaskError(err) && isAuthFailure(err, isDirectIdentity(deps))) {
115
+ if (invalidatedValidationErrors.has(err))
116
+ return;
71
117
  if (err.category === 'auth' && isCredentialReadDenial(err.operation, err.httpStatus, !isDirectIdentity(deps))) {
72
118
  if (!auditInvalidatesCredentialReads.has(deps.client)) {
73
119
  invalidateCredentialReads(deps.pool, deps.poolConfig, deps.client instanceof AutotaskClient ? deps.client : undefined, deps.log);
@@ -53,7 +53,9 @@ export interface HourlyBudget {
53
53
  /** The SDK operations the handler layer drives, bound in ONE place (the mock seam). */
54
54
  export interface ToolOps {
55
55
  /** The MCP request's AbortSignal, when the transport provides one: an abandoned request stops consuming vendor budget. */
56
- invokeRead(client: ToolClient, operation: string, args?: readonly unknown[], opts?: InvokeOptions, signal?: AbortSignal): Promise<unknown>;
56
+ invokeRead(client: ToolClient, operation: string, args?: readonly unknown[], opts?: InvokeOptions & {
57
+ freshMetadata?: true;
58
+ }, signal?: AbortSignal): Promise<unknown>;
57
59
  invokeReadPages(client: ToolClient, operation: string, args: readonly unknown[], onPage: BoundedQueryPageConsumer, opts?: InvokeOptions, signal?: AbortSignal): Promise<BoundedQuerySummary | undefined>;
58
60
  invokeWrite(client: ToolClient, operation: string, args?: readonly unknown[], opts?: InvokeOptions, signal?: AbortSignal): Promise<unknown>;
59
61
  invokeDelete(client: ToolClient, operation: string, args?: readonly unknown[], opts?: InvokeOptions, signal?: AbortSignal): Promise<unknown>;
@@ -106,6 +108,8 @@ export interface ToolDeps {
106
108
  * principal (the token's, or `AUTOTASK_PRINCIPAL` on stdio) and its run scope. Absent on readonly.
107
109
  */
108
110
  write?: WriteDeps;
111
+ /** Effective token scope, when present on a read-only request. */
112
+ runScope?: RunScope;
109
113
  /** The client capabilities the connection's `initialize` declared (2025-era only; absent on a stateless request). */
110
114
  clientCapabilities?: () => ClientCapabilities | undefined;
111
115
  }
@@ -34,6 +34,8 @@ export declare class InputInvalidError extends AutotaskConfigError {
34
34
  * 5. the correlation id stamped on the envelope (and the mirrored text block).
35
35
  */
36
36
  export declare function runTool<A = Record<string, unknown>>(ctx: ToolContext, input: ClosedInput, rawArgs: unknown, extra: unknown, work: (args: A, signal: AbortSignal | undefined, extra: unknown) => Promise<ToolReturn>): Promise<ToolReturn | InputRequiredResult>;
37
+ /** Release and map the refusal under the identity that actually made the request. */
38
+ export declare function toolError(ctx: ToolContext, err: unknown): ToolReturn;
37
39
  /** The typed answer when the MCP request was cancelled before the upstream call settled. */
38
40
  export declare function abortedAnswer(corr: string): ToolReturn;
39
41
  /**
@@ -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). */
@@ -75,12 +76,14 @@ async function frame(ctx, input, rawArgs, extra, work) {
75
76
  return await work(parsed.data, mcpSignal(extra), extra);
76
77
  }
77
78
  catch (err) {
78
- releaseClientOnError(ctx, err);
79
- // V23/FT-5: the request's own credential values ride into the error wrap so a vendor body
80
- // that echoes them is value-scrubbed before it crosses.
81
- return errorContent(err, ctx.correlationId, requestSecrets(ctx), isDirectIdentity(ctx));
79
+ return toolError(ctx, err);
82
80
  }
83
81
  }
82
+ /** Release and map the refusal under the identity that actually made the request. */
83
+ export function toolError(ctx, err) {
84
+ releaseClientOnError(ctx, err);
85
+ return errorContent(err, ctx.correlationId, requestSecrets(ctx), isDirectIdentity(ctx));
86
+ }
84
87
  /**
85
88
  * Stamp the serving unit's correlation id on a finished result (and its mirrored text block).
86
89
  * An `input_required` result is not a tool result: it carries no envelope and is returned untouched.
@@ -270,6 +273,8 @@ export async function readOneItem(ctx, operation, args, signal, opts, projectRaw
270
273
  cleanArgs[0] = bag;
271
274
  }
272
275
  }
276
+ const includeFields = cleanArgs[0]?.includeFields;
277
+ documentReadArgs(ctx, operation, cleanArgs, args);
273
278
  let scopeNote;
274
279
  if (operation.endsWith('.query') && cleanArgs[0] !== null && typeof cleanArgs[0] === 'object' && !Array.isArray(cleanArgs[0])) {
275
280
  const bag = cleanArgs[0];
@@ -284,7 +289,9 @@ export async function readOneItem(ctx, operation, args, signal, opts, projectRaw
284
289
  const bag = (cleanArgs[0] ?? {});
285
290
  cleanArgs[0] = { ...(Array.isArray(bag.fields) && bag.fields.length > 0 ? { labels: true } : {}), maxBytes: FIELD_CATALOG_MAX_BYTES, ...bag };
286
291
  }
287
- 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) => {
288
295
  // #224: a refused cursor the caller passed is the caller's input; a refused vendor continuation is not
289
296
  if (CURSOR_OPS.has(operation) && err?.code === 'RESPONSE_REJECTED' && cleanArgs.some((a) => a !== null && typeof a === 'object' && typeof a.cursor === 'string')) {
290
297
  Object.assign(err, { callerInput: true });
@@ -302,6 +309,15 @@ export async function readOneItem(ctx, operation, args, signal, opts, projectRaw
302
309
  throw errorFromStatus(authFailure.httpStatus, undefined, undefined, authFailure.operation);
303
310
  }
304
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
+ }
305
321
  // Raw evidence must precede deepMarkUntrusted, which replaces excessively nested values.
306
322
  if (projectRaw !== undefined)
307
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';
@@ -63,11 +64,13 @@ export function buildQuery(ctx) {
63
64
  const parentField = staffReadParentFilter(args.resource);
64
65
  const hint = parentField !== undefined
65
66
  ? `call again with {field: "${parentField}", op: "eq", value: "<parent id>"} for a parent or with {field: "id", op: "eq", value: "<row id>"} for a known record`
66
- : isDeletedActivityAuditResource(args.resource)
67
- ? 'pass an audit filter such as {field: "id", op: "exist"} for bounded reads or counts'
68
- : args.resource === 'internal_locations' || args.resource === 'shipping_types'
69
- ? 'call again with {field: "id", op: "eq", value: "<id>"} for a known record, or {field: "id", op: "exist"} for the whole entity'
70
- : 'call again with a scope such as {field: "companyID", op: "eq", value: "<id>"} (time_entries: ticket.companyID), or {field: "id", op: "exist"} for the whole entity';
67
+ : args.resource === 'document_categories'
68
+ ? 'pass a filter on id for a known category or on parentCategoryID for categories under a known parent'
69
+ : isDeletedActivityAuditResource(args.resource)
70
+ ? 'pass an audit filter such as {field: "id", op: "exist"} for bounded reads or counts'
71
+ : args.resource === 'internal_locations' || args.resource === 'shipping_types'
72
+ ? 'call again with {field: "id", op: "eq", value: "<id>"} for a known record, or {field: "id", op: "exist"} for the whole entity'
73
+ : 'call again with a scope such as {field: "companyID", op: "eq", value: "<id>"} (time_entries: ticket.companyID), or {field: "id", op: "exist"} for the whole entity';
71
74
  throw new InputInvalidError(`query: filter is missing or empty; ${hint}`, 'filter');
72
75
  }
73
76
  // #228: totals mode (group_by / sum / count) is the SDK's operations.aggregate over the same filter
@@ -101,10 +104,15 @@ export function buildQuery(ctx) {
101
104
  bag.noteChars = args.note_chars;
102
105
  if (args.acknowledge_unscoped !== undefined)
103
106
  bag.acknowledgeUnscoped = args.acknowledge_unscoped;
104
- 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)
105
109
  .catch((err) => { throw fieldNameInput(scopeRequiredInput(err, 'filter', true), true); });
106
- if (result === undefined)
110
+ if (rawResult === undefined)
107
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) };
108
116
  const v = result;
109
117
  const n = v.count ?? v.total ?? (Array.isArray(v.items) ? v.items.length : undefined);
110
118
  const capped = result.noteCharsTruncated;
@@ -215,15 +223,19 @@ async function outputPathAnswer(ctx, resource, operation, noun, fields, args, si
215
223
  relativePath: args.output_path,
216
224
  });
217
225
  const asTsv = args.format === 'tsv';
226
+ const companies = resource === 'documents' ? documentCompanyScope(ctx) : undefined;
218
227
  const exported = await exportQueryFile({
219
228
  target, fields, format: asTsv ? 'tsv' : 'json', signal,
220
- readPages: consume => ctx.ops.invokeReadPages(ctx.client, operation, [{
229
+ readPages: consume => ctx.ops.invokeReadPages(ctx.client, operation, [scopedDocumentQuery(operation, {
221
230
  filter: args.filter,
222
231
  limit: 500,
223
232
  walk: { maxRows: OUTPUT_MAX_ROWS },
224
233
  ...(args.include_fields === undefined ? {} : { includeFields: args.include_fields }),
225
234
  ...(args.acknowledge_unscoped === undefined ? {} : { acknowledgeUnscoped: args.acknowledge_unscoped }),
226
- }], 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); }),
227
239
  }).catch((error) => { if (error instanceof QueryExportIncompleteError)
228
240
  return undefined; throw error; });
229
241
  if (exported === undefined)