iit-mcp-autotask 0.64.0 → 0.64.2

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
@@ -629,7 +629,8 @@ material).
629
629
  |------|----------|-----------|------|
630
630
  | `CREDENTIAL_MISSING` | `auth` | no | no credential on the request and no server-held default, or a partial tuple (all-or-nothing) |
631
631
  | `CREDENTIAL_MALFORMED` | `validation` | no | a credential value's **shape** cannot be right (quote pair / CR / LF / edge whitespace) — refused before any client is constructed, zero wire; `anomalies` lists the artifacts and `suggestedAction` names the env-load pitfall |
632
- | `UNAUTHORIZED` | `auth` | no | the vendor rejected a credential that **was** sent (401/403). With anomalous values this envelope is annotated (`credentialShape`, `shapeDiagnostic`, `suggestedAction`); with clean values it is exactly the fixed envelope |
632
+ | `UNAUTHORIZED` | `auth` | no | a vendor 401 or a 403 treated as a credential or impersonation refusal. With anomalous values this envelope is annotated (`credentialShape`, `shapeDiagnostic`, `suggestedAction`); with clean values it is exactly the fixed envelope |
633
+ | `FORBIDDEN` | `auth` | no | a vendor 403 on an organizational-resource or daily-availability read with a resolved identity and no impersonation. The reason is `UPSTREAM_ERROR` with permission guidance. |
633
634
  | `HOST_POLICY_DENIED` | `policy` | no | the origin is absent/unusable/not allow-listed (never the value echoed) |
634
635
 
635
636
  ## Per-request credential model
@@ -715,16 +716,18 @@ per-write override. Omit the argument to retain the request's default.
715
716
 
716
717
  Under `stdio` the process environment **is** the trust boundary: the three credentials + zone are
717
718
  required at boot (`AUTOTASK_API_INTEGRATION_CODE`, `AUTOTASK_USERNAME`, `AUTOTASK_SECRET`,
718
- `AUTOTASK_BASE_URL`; optional `AUTOTASK_IMPERSONATION_RESOURCE_ID`); one process-lifetime client is
719
- resolved from them through the SDK client pool. Missing required env is a **boot failure**: the process exits non-zero
720
- with a typed config error naming the variable — never a value (fail-fast, before any listener).
719
+ `AUTOTASK_BASE_URL`; optional `AUTOTASK_IMPERSONATION_RESOURCE_ID`). The SDK pool resolves the
720
+ initial client from that identity, and stdio keeps that client for the connection lifetime. Missing
721
+ required env is a **boot failure**. The process exits non-zero with a typed config error naming the
722
+ variable before opening a listener.
721
723
 
722
724
  Credential hygiene (both transports): the three credential values are **never logged, never written
723
725
  to disk, never cached across requests except via the sanctioned pool key (a SHA-256 digest — raw
724
726
  credentials never in keys, logs or eviction messages), never in error messages, and never in any
725
- tool input schema**. Logging redacts the credential header names. On a vendor `401` (or an
726
- impersonation-scope `403`) the pooled client entry is deleted — a stale identity is never
727
- negative-cached or replayed.
727
+ tool input schema**. Logging redacts the credential header names. A vendor `401` or an
728
+ impersonation-scope `403` evicts the exact pooled client. On organizational-resource,
729
+ daily-availability, or registered metadata reads, a `401` or an impersonated `403` also
730
+ clears that identity's SDK read and metadata caches. A `403` classified by the SDK as maintenance uses the maintenance path.
728
731
 
729
732
  ## Per-tenant pool & cache
730
733
 
@@ -736,8 +739,9 @@ guards (rate limiter, 429 cooldown) — a worse security posture, not a safer on
736
739
  - **Pool** — the SDK's `createClientPool` (no server-side wrapper; issue #252): a bounded LRU of
737
740
  tenant clients at the SDK default `maxSize` 128. Key = SHA-256 digest of the
738
741
  **normalised credential tuple** (user, integration code, secret, resolved base URL,
739
- impersonation id). Eviction is logged without values. A vendor `401` (or an
740
- impersonation-scope `403`) deletes the entry (no negative caching).
742
+ impersonation id). Eviction is logged without values. A vendor `401` or a `403` treated as an
743
+ identity refusal deletes the entry. A resolved identity without impersonation keeps its pooled
744
+ client after a `403` from the organizational-resource or daily-availability reads.
741
745
  - **Cache** — `AUTOTASK_CACHE=on` (default) sends no cache block — the SDK's default-on caches
742
746
  apply to each pooled tenant client (SDK 0.9.0's default-on change: read ~5 min, the reference
743
747
  tables ~1 h, field metadata ~5 min). Repeated reads of the same record are served from that
@@ -750,11 +754,13 @@ guards (rate limiter, 429 cooldown) — a worse security posture, not a safer on
750
754
  `AUTOTASK_CACHE=off` disables that index; results remain live-only with `index.state: "off"`.
751
755
  Cold/building indexes and capped live searches can miss companies: inspect the returned metadata.
752
756
  - **Boundaries — never relaxed:** in-process only (never on disk), **per-tenant** (one tenant's
753
- cached records never answer another tenant's request), TTL-bounded, cleared on eviction and
754
- on `401`. Client-local budgets and cooldown remain scoped; the SDK's shared object/origin
757
+ cached records never answer another tenant's request) and TTL-bounded. The SDK can retain the
758
+ exact tuple's shared read cache across client eviction. A `401` or impersonated `403` on a staff or registered metadata read
759
+ clears it before eviction. Client-local budgets and cooldown remain scoped. The SDK's shared object/origin
755
760
  admission deliberately coordinates clients in the same runtime (see [Gateway assumptions](#gateway-assumptions)).
756
- - **stdio** uses one process-lifetime client (the env is the whole identity) — no pool, and the
757
- cache/limiter state is that single tenant's by construction.
761
+ - **stdio** resolves its environment identity through the SDK pool and keeps the initial client
762
+ for the connection lifetime, including after pool-entry eviction. The credential-refusal cache
763
+ rules also clear that retained client’s SDK caches when applicable.
758
764
  - **Multi-process gateways:** pool/cache/limiter state is per-process; an N-process gateway runs N
759
765
  independent trackers (documented consequence, security review C7.2).
760
766
 
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,413 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,435 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": 1413,
483
+ "backingRegistryOperations": 1435,
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": {}
@@ -55,6 +55,8 @@ export declare const CATALOG: CatalogData;
55
55
  export declare const RECORDS: readonly CapabilityRecord[];
56
56
  /** The record for one exact registry key, or `undefined` (unknown keys are never guessed). */
57
57
  export declare function recordById(operation: string): CapabilityRecord | undefined;
58
+ /** resolveAny looks up a camel-case SDK accessor but echoes the caller's spelling. */
59
+ export declare function canonicalResolverResource(resource: string): string | undefined;
58
60
  /**
59
61
  * The tool that serves each backing operation. The served catalog's `tool` column carries this
60
62
  * name when the tool is registered in THIS deployment (its profile + toolsets), else `null`:
@@ -64,6 +66,17 @@ export declare function recordById(operation: string): CapabilityRecord | undefi
64
66
  export declare const TOOL_NAME_BY_OP: Readonly<Record<string, string>>;
65
67
  /** The tool that serves one registry key: the table above, else `autotask_query` for any `<resource>.query` read (#228). */
66
68
  export declare function toolForOp(operation: string): string | undefined;
69
+ /** Parent filters for the staff reads whose native routes and global queries use different locators. */
70
+ export declare function staffReadParentFilter(resource: string): string | undefined;
71
+ export declare function isStaffReadOperation(operation: unknown): operation is string;
72
+ /** Exact registered metadata reads can settle on a shared wire request. */
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: {
76
+ operation?: unknown;
77
+ httpStatus?: unknown;
78
+ category?: unknown;
79
+ }): boolean;
67
80
  /** The served tool for this row's operation in a deployment serving `served`, or `null`. */
68
81
  export declare function servedToolName(row: CatalogRow, served: ReadonlySet<string>): string | null;
69
82
  /** The registry keys projected onto an MCP tool name (the reverse of {@link TOOL_NAME_BY_OP}); empty when none. */
@@ -108,7 +121,7 @@ export declare function sdkCacheOptions(cache: 'on' | 'off'): Pick<AutotaskConfi
108
121
  * fails the boot (or the CI test) instead of quietly shipping a tool surface that no longer
109
122
  * describes the SDK behind it.
110
123
  */
111
- export declare const BUILT_AGAINST_PLAN_HASH = "fe0c9ce6a957bb730c1bdb9fb46498e61e2d04cc1cdd861d796ac26f982ab505";
124
+ export declare const BUILT_AGAINST_PLAN_HASH = "51888554f455b96e13c50591342fa516b095065762430b783201ac7a995a0901";
112
125
  /**
113
126
  * Fail fast when the installed SDK's plan has moved out from under this surface.
114
127
  * Called at boot (main.ts) and safe to call repeatedly (pure comparison).
@@ -36,6 +36,17 @@ const RECORD_BY_ID = new Map(RECORDS.map((r) => [r.id, r]));
36
36
  export function recordById(operation) {
37
37
  return RECORD_BY_ID.get(operation);
38
38
  }
39
+ function sdkResourceAccessor(resource) {
40
+ return resource.replace(/_([^_])/g, (_, letter) => letter.toUpperCase());
41
+ }
42
+ const RESOURCE_BY_ACCESSOR = new Map(RECORDS.map(({ resource }) => [sdkResourceAccessor(resource), resource]));
43
+ /** resolveAny looks up a camel-case SDK accessor but echoes the caller's spelling. */
44
+ export function canonicalResolverResource(resource) {
45
+ // The SDK's conversion requires each segment after an underscore to be nonempty.
46
+ if (resource.includes('__') || resource.endsWith('_'))
47
+ return undefined;
48
+ return RESOURCE_BY_ACCESSOR.get(sdkResourceAccessor(resource));
49
+ }
39
50
  // ---------------------------------------------------------------------------
40
51
  // The served tool per backing operation (the catalog's `tool` column)
41
52
  // ---------------------------------------------------------------------------
@@ -93,6 +104,27 @@ export const TOOL_NAME_BY_OP = {
93
104
  export function toolForOp(operation) {
94
105
  return TOOL_NAME_BY_OP[operation] ?? (operation.endsWith('.query') && recordById(operation)?.effect === 'read' ? 'autotask_query' : undefined);
95
106
  }
107
+ /** Parent filters for the staff reads whose native routes and global queries use different locators. */
108
+ export function staffReadParentFilter(resource) {
109
+ if (resource === 'organizational_resources')
110
+ return 'organizationalLevelAssociationID';
111
+ if (resource === 'resource_daily_availabilities')
112
+ return 'resourceID';
113
+ return undefined;
114
+ }
115
+ export function isStaffReadOperation(operation) {
116
+ const record = typeof operation === 'string' ? recordById(operation) : undefined;
117
+ return record?.effect === 'read' && staffReadParentFilter(record.resource) !== undefined;
118
+ }
119
+ /** Exact registered metadata reads can settle on a shared wire request. */
120
+ export function isRegisteredMetadataRead(operation) {
121
+ const record = typeof operation === 'string' ? recordById(operation) : undefined;
122
+ return record?.effect === 'read' && /^(getEntityInfo|getFieldInfo|getUdfInfo)$/.test(record.operation);
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);
127
+ }
96
128
  /** The served tool for this row's operation in a deployment serving `served`, or `null`. */
97
129
  export function servedToolName(row, served) {
98
130
  const tool = toolForOp(row.operation) ?? (row.effect === 'read' ? undefined : 'autotask_write');
@@ -190,7 +222,7 @@ export function sdkCacheOptions(cache) {
190
222
  * fails the boot (or the CI test) instead of quietly shipping a tool surface that no longer
191
223
  * describes the SDK behind it.
192
224
  */
193
- export const BUILT_AGAINST_PLAN_HASH = 'fe0c9ce6a957bb730c1bdb9fb46498e61e2d04cc1cdd861d796ac26f982ab505';
225
+ export const BUILT_AGAINST_PLAN_HASH = '51888554f455b96e13c50591342fa516b095065762430b783201ac7a995a0901';
194
226
  /**
195
227
  * Fail fast when the installed SDK's plan has moved out from under this surface.
196
228
  * Called at boot (main.ts) and safe to call repeatedly (pure comparison).
@@ -1,10 +1,10 @@
1
1
  /** SDK client construction (base options, placeholder, stdio client) and the default SDK ops bundle (issue #91). */
2
2
  import { statusBasedVendorCode } from '../results/errors.js';
3
- import { AutotaskClient } from 'node-autotask';
3
+ 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 { sdkCacheOptions } from '../catalog-data.js';
7
+ import { isRegisteredMetadataRead, sdkCacheOptions } from '../catalog-data.js';
8
8
  import { captureReadRuntime } from '../read-runtime.js';
9
9
  // ---------------------------------------------------------------------------
10
10
  // SDK client construction
@@ -14,6 +14,23 @@ export const PLACEHOLDER_ORIGIN = 'https://no-autotask-origin.invalid';
14
14
  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
+ // SDK classifications here are fixed tokens. A vendor-origin SDK code must contain a digit.
18
+ const METADATA_AUDIT_CODES = new Set([
19
+ 'ABORTED', 'HOST_POLICY_DENIED', 'MAINTENANCE', 'REDIRECT_BLOCKED', 'RESPONSE_REJECTED', 'RESPONSE_TOO_LARGE',
20
+ 'RATE_LIMITED', 'RATE_LIMITED_COOLDOWN', 'CIRCUIT_BREAKER_OPEN',
21
+ 'TIMEOUT', 'NETWORK_ERROR', 'INVALID_RESPONSE', 'UNEXPECTED_CONTENT_TYPE', 'EMPTY_RESPONSE',
22
+ ]);
23
+ function auditErrorCode(code, operation, status) {
24
+ if (typeof code !== 'string')
25
+ return undefined;
26
+ if (isRegisteredMetadataRead(operation)) {
27
+ // A terminal SDK failure can carry the status from an earlier retry.
28
+ if (METADATA_AUDIT_CODES.has(code))
29
+ return code;
30
+ return status !== undefined && status >= 300 ? errorFromStatus(status, undefined).code : 'UPSTREAM_ERROR';
31
+ }
32
+ return code === 'MAINTENANCE' ? code : statusBasedVendorCode(operation, status) ?? code;
33
+ }
17
34
  /**
18
35
  * The deployment-wide SDK options every client this factory builds gets (the agent profile +
19
36
  * the env overrides + the cache off switch + the zero maintenance wait + the literal-IP host
@@ -59,9 +76,7 @@ export function buildSdkBaseOptions(config, log) {
59
76
  const e = event;
60
77
  const operation = typeof e.operation === 'string' ? e.operation : undefined;
61
78
  const status = typeof e.status === 'number' ? e.status : undefined;
62
- const errorCode = typeof e.errorCode === 'string' && e.errorCode !== 'MAINTENANCE'
63
- ? statusBasedVendorCode(operation, status) ?? e.errorCode
64
- : e.errorCode === 'MAINTENANCE' ? 'MAINTENANCE' : undefined;
79
+ const errorCode = auditErrorCode(e.errorCode, operation, status);
65
80
  log.info('autotask request', {
66
81
  ...(typeof e.correlationId === 'string' ? { correlationId: e.correlationId } : {}),
67
82
  ...(operation !== undefined ? { operation } : {}),
@@ -1,6 +1,14 @@
1
+ /** Deriving a tool context from the deps, and releasing a client on error (issue #91). */
2
+ import { AutotaskClient, type AutotaskConfig } from 'node-autotask';
3
+ import type { ClientPool } from 'node-autotask/pool';
4
+ import type { Logger } from '../../logger.js';
1
5
  import type { ToolDeps, ToolContext } from './types.js';
6
+ /** Resolve the SDK client and bind invalidation to its exact pool key. */
7
+ export declare function getPooledClient(pool: ClientPool, config: AutotaskConfig, log: Logger): AutotaskClient;
2
8
  /** Derive the context the registrations share. */
3
9
  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. */
11
+ export declare function isDirectIdentity(deps: Pick<ToolDeps, 'poolConfig'>): boolean;
4
12
  /**
5
13
  * A vendor 401 (or impersonation-scope 401/403) deletes the pooled entry so a stale identity is
6
14
  * not negative-cached and replayed (security S1/C1.8, S3/C3.5): the next request with the same
@@ -1,7 +1,46 @@
1
1
  /** Deriving a tool context from the deps, and releasing a client on error (issue #91). */
2
- import { isAutotaskError } from 'node-autotask';
2
+ import { AutotaskClient, isAutotaskError } from 'node-autotask';
3
3
  import { isAuthFailure } from '../results/errors.js';
4
- import { recordById, toolDescription, untrustedFieldsOf } from '../catalog-data.js';
4
+ import { isRegisteredMetadataRead, isStaffReadOperation, recordById, toolDescription, untrustedFieldsOf } from '../catalog-data.js';
5
+ // A real client with this hook handles eviction once per wire refusal, even if multiple readers share the result.
6
+ const auditInvalidatesCredentialReads = new WeakSet();
7
+ function isCredentialReadDenial(operation, status, impersonated) {
8
+ return (status === 401 || (status === 403 && impersonated)) &&
9
+ (isStaffReadOperation(operation) || isRegisteredMetadataRead(operation));
10
+ }
11
+ function invalidateCredentialReads(pool, config, client, log) {
12
+ // A pinned stdio or in-flight client can outlive its pool entry. Clear its stores if the pool did not.
13
+ const readCache = client?.http.readCache;
14
+ const fieldCache = client?.http.fieldCache;
15
+ const readEpoch = readCache?.epoch;
16
+ const fieldEpoch = fieldCache?.epoch;
17
+ const removed = pool.delete(config, { clearCachedReads: true });
18
+ if (readCache?.epoch === readEpoch)
19
+ readCache?.clear();
20
+ if (fieldCache?.epoch === fieldEpoch)
21
+ fieldCache?.clear();
22
+ if (removed)
23
+ log.info('deleted pooled client after credential refusal', { removed, poolSize: pool.size });
24
+ }
25
+ /** Resolve the SDK client and bind invalidation to its exact pool key. */
26
+ export function getPooledClient(pool, config, log) {
27
+ const client = pool.get({
28
+ ...config,
29
+ onAudit(event) {
30
+ const { status, operation, errorCode, notSent } = event;
31
+ // The SDK can retain a machine code containing digits for a real status error.
32
+ // Its own abort, maintenance and response-policy codes do not describe an auth denial.
33
+ const authCode = errorCode === (status === 401 ? 'UNAUTHORIZED' : 'FORBIDDEN') ||
34
+ (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);
38
+ }
39
+ config.onAudit?.(event);
40
+ },
41
+ });
42
+ return client;
43
+ }
5
44
  /** Derive the context the registrations share. */
6
45
  export function deriveToolContext(deps, served = new Set()) {
7
46
  return {
@@ -16,6 +55,10 @@ export function deriveToolContext(deps, served = new Set()) {
16
55
  description: toolDescription,
17
56
  };
18
57
  }
58
+ /** Only a resolved direct identity can treat a staff 403 as an entity permission refusal. */
59
+ export function isDirectIdentity(deps) {
60
+ return deps.poolConfig !== undefined && deps.poolConfig.impersonationResourceId === undefined;
61
+ }
19
62
  /**
20
63
  * A vendor 401 (or impersonation-scope 401/403) deletes the pooled entry so a stale identity is
21
64
  * not negative-cached and replayed (security S1/C1.8, S3/C3.5): the next request with the same
@@ -24,7 +67,13 @@ export function deriveToolContext(deps, served = new Set()) {
24
67
  export function releaseClientOnError(deps, err) {
25
68
  if (deps.pool === undefined || deps.poolConfig === undefined)
26
69
  return;
27
- if (isAutotaskError(err) && isAuthFailure(err)) {
70
+ if (isAutotaskError(err) && isAuthFailure(err, isDirectIdentity(deps))) {
71
+ if (err.category === 'auth' && isCredentialReadDenial(err.operation, err.httpStatus, !isDirectIdentity(deps))) {
72
+ if (!auditInvalidatesCredentialReads.has(deps.client)) {
73
+ invalidateCredentialReads(deps.pool, deps.poolConfig, deps.client instanceof AutotaskClient ? deps.client : undefined, deps.log);
74
+ }
75
+ return;
76
+ }
28
77
  const removed = deps.pool.delete(deps.poolConfig);
29
78
  deps.log.info('deleted pooled client after credential refusal', { removed, poolSize: deps.pool.size });
30
79
  }
@@ -4,6 +4,7 @@ import { baseHostAllowed, normalizeBaseUrl } from '../../base-hosts.js';
4
4
  import { CREDENTIAL_LOAD_HINT } from '../../credential.js';
5
5
  import { captureReadRuntime } from '../read-runtime.js';
6
6
  import { buildSdkBaseOptions, buildPlaceholderClient } from './client.js';
7
+ import { getPooledClient } from './derive.js';
7
8
  /**
8
9
  * The five origin facts of one request, derived from the header origin and the deployment default. They are kept together on purpose:
9
10
  * `callerNamed` is true for a header origin that was given but is unparseable, and that one fact withholds the default identity, picks
@@ -173,7 +174,7 @@ export function createHttpScopeResolver(config, log, pool, baseOptions) {
173
174
  // deployment-wide default alone 500'd an allow-listed NON-default caller origin at client
174
175
  // construction (HostPolicyDeniedError out of the per-request factory).
175
176
  const poolConfig = poolConfigFor(creds, baseNormalized, defaultOrigin, baseOptions);
176
- const client = pool.get(poolConfig);
177
+ const client = getPooledClient(pool, poolConfig, log);
177
178
  captureReadRuntime(client);
178
179
  return { client, origin: baseNormalized.origin, poolConfig };
179
180
  },
@@ -11,14 +11,14 @@
11
11
  * to 10 `items`) and the read-backed tools all drive it, so every read passes the same gates in
12
12
  * the same order.
13
13
  */
14
- import { AutotaskConfigError } from 'node-autotask';
14
+ import { AutotaskConfigError, errorFromStatus } from 'node-autotask';
15
15
  import { stripUntrustedDeep } from 'node-autotask/untrusted';
16
16
  import { assertFilterShape, QUERY_LIMIT, QUERY_MAX_ROWS } from './schemas.js';
17
- import { RECORDS, toolForOp } from './catalog-data.js';
17
+ import { isRegisteredMetadataRead, RECORDS, staffReadParentFilter, toolForOp } from './catalog-data.js';
18
18
  import { AUTOTASK_BASE_PATH } from '../base-hosts.js';
19
- import { releaseClientOnError } from './context/derive.js';
20
- import { abortedResult, closedArgsError, errorContent, isShapeOnlyVendorOperation, refusalContent } from './results/errors.js';
21
- import { crossResourceUntrusted, isFileOperation, markFilePayload, markResult, markServerField } from './results/untrusted.js';
19
+ import { isDirectIdentity, releaseClientOnError } from './context/derive.js';
20
+ import { abortedResult, closedArgsError, errorContent, isShapeOnlyVendorOperation, refusalContent, resolveFaultCode, statusBasedVendorCode } from './results/errors.js';
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
24
  import { scopeRequiredInput } from './scope-guard.js';
@@ -78,7 +78,7 @@ async function frame(ctx, input, rawArgs, extra, work) {
78
78
  releaseClientOnError(ctx, err);
79
79
  // V23/FT-5: the request's own credential values ride into the error wrap so a vendor body
80
80
  // that echoes them is value-scrubbed before it crosses.
81
- return errorContent(err, ctx.correlationId, requestSecrets(ctx));
81
+ return errorContent(err, ctx.correlationId, requestSecrets(ctx), isDirectIdentity(ctx));
82
82
  }
83
83
  }
84
84
  /**
@@ -165,6 +165,9 @@ const OWN_STAMP_OPS = new Set(['contracts.profitability', 'operations.revenueRol
165
165
  * `autotask_read` only). The name is NOT `queryable`: the SDK row already carries `queryable: string[]`.
166
166
  */
167
167
  function annotateCatalogRows(result) {
168
+ // The SDK's call-owned refusal evidence was already evaluated before projection.
169
+ if (result !== null && typeof result === 'object')
170
+ delete result.authFailure;
168
171
  // 0.39.0 (#282): the truncation note is SDK-built (an enum reason, byte counts, resource keys), never vendor
169
172
  // text; `reason` and `note` share names with vendor free-text fields, so they are recorded server-built.
170
173
  const truncation = result?.truncation;
@@ -182,9 +185,43 @@ function annotateCatalogRows(result) {
182
185
  const operation = typeof resource === 'string' ? `${resource}.query` : undefined;
183
186
  const catalogRow = row;
184
187
  catalogRow.queryOperation = operation !== undefined && toolForOp(operation) === 'autotask_query' ? operation : null;
185
- if (isShapeOnlyVendorOperation(operation) && catalogRow.error != null) {
186
- // The SDK's row error carries vendor text and a code without trusted HTTP status.
187
- catalogRow.error = { code: 'UPSTREAM_ERROR', message: 'Autotask could not provide metadata for this resource.' };
188
+ if (catalogRow.error != null) {
189
+ // A folded row error carries vendor text and a code without trusted HTTP status.
190
+ const error = { code: 'UPSTREAM_ERROR', message: 'Autotask could not provide metadata for this resource.' };
191
+ markServerField(error, 'message', 'server');
192
+ catalogRow.error = error;
193
+ }
194
+ }
195
+ }
196
+ /** Bulk results carry item faults as data, outside the thrown-error boundary. */
197
+ function redactBulkFaults(result) {
198
+ const rows = result?.results;
199
+ if (!Array.isArray(rows))
200
+ return;
201
+ for (const row of rows) {
202
+ if (row?.error == null || typeof row.resource !== 'string')
203
+ continue;
204
+ const operation = `${row.resource}.get`;
205
+ if (!isShapeOnlyVendorOperation(operation))
206
+ continue;
207
+ const httpStatus = typeof row.error.httpStatus === 'number' ? row.error.httpStatus : undefined;
208
+ const code = statusBasedVendorCode(operation, httpStatus) ?? (row.error.code === 'NOT_FOUND' ? 'NOT_FOUND' : 'UPSTREAM_ERROR');
209
+ row.error = {
210
+ code,
211
+ ...(httpStatus === undefined ? {} : { httpStatus }),
212
+ message: code === 'NOT_FOUND'
213
+ ? 'No record was visible to this API user at the requested ID.'
214
+ : 'Autotask could not provide this record.',
215
+ };
216
+ }
217
+ }
218
+ function redactResolveFaults(result) {
219
+ const rows = result?.results;
220
+ if (!Array.isArray(rows))
221
+ return;
222
+ for (const row of rows) {
223
+ if (typeof row?.resource === 'string' && typeof row.error === 'string') {
224
+ row.error = resolveFaultCode(row.resource, row.error);
188
225
  }
189
226
  }
190
227
  }
@@ -256,6 +293,15 @@ export async function readOneItem(ctx, operation, args, signal, opts, projectRaw
256
293
  });
257
294
  if (result === undefined)
258
295
  return { aborted: true, result: undefined };
296
+ if (operation === 'operations.fieldCatalog') {
297
+ // SDK rows carry the normalized, validated targets, independent of which metadata refusal won.
298
+ const { authFailure, rows } = result ?? {};
299
+ if (authFailure !== undefined && (authFailure.httpStatus === 401 || (authFailure.httpStatus === 403 && !isDirectIdentity(ctx))) &&
300
+ rows?.some(({ resource }) => staffReadParentFilter(resource) !== undefined) &&
301
+ isRegisteredMetadataRead(authFailure.operation) && rows.some(({ resource }) => authFailure.operation.startsWith(`${resource}.`))) {
302
+ throw errorFromStatus(authFailure.httpStatus, undefined, undefined, authFailure.operation);
303
+ }
304
+ }
259
305
  // Raw evidence must precede deepMarkUntrusted, which replaces excessively nested values.
260
306
  if (projectRaw !== undefined)
261
307
  return { result: projectRaw(result), ...(scopeNote !== undefined ? { scopeNote } : {}) };
@@ -264,7 +310,11 @@ export async function readOneItem(ctx, operation, args, signal, opts, projectRaw
264
310
  // Issue #1: wrap the SDK result's externally-sourced free text — envelope-shaped results are
265
311
  // walked deeply (items[] arrays included).
266
312
  // Arrays too (final review R2: the *.search and find helpers answer arrays).
267
- const projected = result !== null && typeof result === 'object' ? markResult(result, crossResourceUntrusted()) : result;
313
+ const projected = result !== null && typeof result === 'object' ? markReadResult(operation, result) : result;
314
+ if (operation === 'operations.fetchByIds')
315
+ redactBulkFaults(projected);
316
+ if (operation === 'operations.resolveAny')
317
+ redactResolveFaults(projected);
268
318
  if (isFileOperation(operation))
269
319
  markFilePayload(projected);
270
320
  // #224: the posted-state reads' nextCursor goes back verbatim as opts.cursor; the 500 cap would cut it
@@ -10,7 +10,7 @@
10
10
  */
11
11
  import { AutotaskConfigError } from 'node-autotask';
12
12
  import { QUERY_INPUT, QUERY_LIMIT, assertFilterShape, closedInput } from './schemas.js';
13
- import { isDeletedActivityAuditResource } from './catalog-data.js';
13
+ import { isDeletedActivityAuditResource, staffReadParentFilter } from './catalog-data.js';
14
14
  import { abortedAnswer, InputInvalidError } from './dispatch.js';
15
15
  import { runAggregate } from './aggregate.js';
16
16
  import { markResult, markServerField, PROVENANCE, sanitiseVendorOutput } from './results/untrusted.js';
@@ -60,11 +60,14 @@ export function buildQuery(ctx) {
60
60
  const conditions = Array.isArray(args.filter) ? args.filter : args.filter?.filter;
61
61
  if (args.filter === undefined || (Array.isArray(conditions) && conditions.length === 0)) {
62
62
  // one sentence that names the scope to add (data.message and reasons[].detail both carry it whole)
63
- const hint = isDeletedActivityAuditResource(args.resource)
64
- ? 'pass an audit filter such as {field: "id", op: "exist"} for bounded reads or counts'
65
- : args.resource === 'internal_locations' || args.resource === 'shipping_types'
66
- ? 'call again with {field: "id", op: "eq", value: "<id>"} for a known record, or {field: "id", op: "exist"} for the whole entity'
67
- : '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';
63
+ const parentField = staffReadParentFilter(args.resource);
64
+ const hint = parentField !== undefined
65
+ ? `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';
68
71
  throw new InputInvalidError(`query: filter is missing or empty; ${hint}`, 'filter');
69
72
  }
70
73
  // #228: totals mode (group_by / sum / count) is the SDK's operations.aggregate over the same filter
@@ -21,8 +21,8 @@ import { projectTimeEntryVerification } from './time-entry-verification.js';
21
21
  import { AutotaskConfigError } from 'node-autotask';
22
22
  import { effectiveRequiredFields } from 'node-autotask/operations';
23
23
  import { UDF_MERGE_NOTE, UDF_NONE, UDF_ROWS_NOTE, associationFields, associationRules, caveatNotes, fieldSemanticsNote, constraintNotes, coupledNotes, dateConventionNotes, statusScopeNote, udfDefinitionRows, udfMergeNote, udfMoreNote, udfUnavailable } from './write-guidance.js';
24
- import { CATALOG, RECORDS, SDK_VERSION, UDF_CAPABLE, isDeletedActivityAuditResource, opsForTool, recordById, servedToolName, toolForOp, untrustedFieldsOf } from './catalog-data.js';
25
- import { releaseClientOnError } from './context/derive.js';
24
+ import { CATALOG, RECORDS, SDK_VERSION, UDF_CAPABLE, isDeletedActivityAuditResource, opsForTool, recordById, servedToolName, staffReadParentFilter, toolForOp, untrustedFieldsOf } from './catalog-data.js';
25
+ import { isDirectIdentity, releaseClientOnError } from './context/derive.js';
26
26
  import {} from './context/types.js';
27
27
  import { abortedAnswer, FIELD_CATALOG_MAX_BYTES, InputInvalidError, readOneItem, requestSecrets } from './dispatch.js';
28
28
  import { zoneClock } from './clock.js';
@@ -322,6 +322,20 @@ function servedUdfFields(raw, readCall) {
322
322
  fields: sanitiseVendorOutput(markResult(rows, ['name', 'label', 'picklist'])),
323
323
  };
324
324
  }
325
+ /** An item read takes a row ID. A native list takes its parent ID. */
326
+ function staffIdReadExample(rec) {
327
+ if (rec.effect !== 'read' || staffReadParentFilter(rec.resource) === undefined)
328
+ return undefined;
329
+ const op = rec.id.slice(rec.resource.length + 1);
330
+ if (op !== 'get' && op !== 'listByParent')
331
+ return undefined;
332
+ const id = op === 'get' ? 3 : 7;
333
+ return {
334
+ exampleArgs: [id],
335
+ example: `autotask_read {operation:"${rec.id}", args:[${id}]}`,
336
+ note: op === 'get' ? 'Pass the row ID as a number or decimal string.' : 'Pass the parent ID as a number or decimal string.',
337
+ };
338
+ }
325
339
  /**
326
340
  * MCP-shaped guidance for one operation, placed BEFORE the SDK record (#109): the record's own
327
341
  * `examples` are SDK JavaScript and its query grammar sits after long caveats. Queries get an `autotask_read` example; create/update get the required and read-only field names
@@ -331,11 +345,21 @@ function servedUdfFields(raw, readCall) {
331
345
  async function guidanceFor(ctx, rec, reachable) {
332
346
  const op = rec.id.slice(rec.resource.length + 1);
333
347
  if (rec.effect === 'read' && op === 'query') {
348
+ const parentField = staffReadParentFilter(rec.resource);
349
+ if (parentField !== undefined) {
350
+ return {
351
+ exampleArgs: [{ filter: [{ field: parentField, op: 'eq', value: 7 }], limit: 10 }],
352
+ example: `autotask_query {resource:"${rec.resource}", filter:[{field:"${parentField}",op:"eq",value:"<parent id>"}], limit:10}`,
353
+ };
354
+ }
334
355
  return {
335
356
  exampleArgs: [{ filter: [{ field: 'id', op: 'gt', value: 0 }], limit: 10 }],
336
357
  example: `autotask_read {operation:"${rec.id}", args:[{filter:[{field:"id",op:"gt",value:0}],limit:10}]}`,
337
358
  };
338
359
  }
360
+ const staffExample = staffIdReadExample(rec);
361
+ if (staffExample !== undefined)
362
+ return staffExample;
339
363
  if (op === 'getFieldInfo' && rec.effect === 'read') {
340
364
  return { expensive: FIELD_INFO_EXPENSIVE, instead: fieldLookupCall(rec.resource) };
341
365
  }
@@ -544,14 +568,30 @@ function operatorIdDescription(rec, key) {
544
568
  ? 'parentId requires a positive signed 32-bit category ID as a JSON integer.'
545
569
  : `${key} requires a positive safe integer JSON number.`;
546
570
  }
571
+ const STAFF_COUNT_GUIDANCE = 'An authorization refusal on the count stops the query. An eligible count failure or a blind count allows the bounded walk with a scopeNote.';
572
+ function staffQueryArgs(text) {
573
+ return text.replace(/a count that fails or is blind lets the walk run and the result[’']s scopeNote says so/, STAFF_COUNT_GUIDANCE);
574
+ }
547
575
  /** Served record: caveats projected, MCP argument restrictions applied and the SDK's own test list dropped. */
548
576
  function servedRecord(rec) {
549
577
  const projected = { ...projectCaveats(rec) };
550
578
  delete projected.tests;
579
+ const staffExample = staffIdReadExample(rec);
580
+ if (staffExample !== undefined)
581
+ projected.examples = [staffExample.example];
551
582
  const md = projected.metadata;
552
583
  const usage = servedUsage(rec);
553
584
  if (usage !== undefined && usage !== md?.usage)
554
585
  projected.metadata = { ...md, usage };
586
+ const params = rec.inputSchema.params;
587
+ const argsText = rec.metadata?.args;
588
+ if (rec.operation === 'query' && staffReadParentFilter(rec.resource) !== undefined) {
589
+ if (typeof params?.description === 'string') {
590
+ projected.inputSchema = { ...rec.inputSchema, params: { ...params, description: staffQueryArgs(params.description) } };
591
+ }
592
+ if (typeof argsText === 'string')
593
+ projected.metadata = { ...projected.metadata, args: staffQueryArgs(argsText) };
594
+ }
555
595
  const staffArgs = staffAttachmentArgs(rec);
556
596
  const args = staffArgs ?? operatorWriteArgs(rec);
557
597
  if (args !== undefined) {
@@ -583,6 +623,19 @@ function compactUsage(rec, summary) {
583
623
  const usage = servedUsage(rec);
584
624
  if (usage === undefined)
585
625
  return usage;
626
+ const parentField = staffReadParentFilter(rec.resource);
627
+ if (parentField !== undefined) {
628
+ const visibility = rec.resource === 'organizational_resources'
629
+ ? 'Visibility depends on Organizational Structure activation and API-user permissions.'
630
+ : 'Visibility depends on enabled features and API-user permissions.';
631
+ const caveats = `${visibility} Empty results are inconclusive. Staff parentage does not establish company ownership.`;
632
+ if (rec.operation === 'query' || rec.operation === 'count') {
633
+ return `Filter on ${parentField} to select a parent. ${caveats} ${usage}`;
634
+ }
635
+ if (rec.operation === 'listByParent') {
636
+ return `Returns one native page with items and hasMore. No filter, limit, or raw cursor. ${caveats} ${usage}`;
637
+ }
638
+ }
586
639
  if (rec.resource === 'knowledge_base_articles') {
587
640
  if (rec.operation === 'update' && summary) {
588
641
  return `Update uses the approved category route; articleCategoryID is read-only. ${usage}`;
@@ -624,7 +677,9 @@ function summariseRecord(ctx, operation, viaTool) {
624
677
  ...(tool !== undefined ? { tool, ...toolServed(ctx, tool) } : {}),
625
678
  purpose: capText(text(md.purpose) || text(row?.purpose), SUMMARY_CAPS.purpose, 'purpose', cut),
626
679
  requiredArgs: row?.requiredArgs ?? [],
627
- args: capText(staffAttachmentArgs(rec) ?? operatorWriteArgs(rec) ?? text(md.args), SUMMARY_CAPS.args, 'args', cut),
680
+ args: capText(rec.operation === 'query' && staffReadParentFilter(rec.resource) !== undefined
681
+ ? `${STAFF_COUNT_GUIDANCE} ${staffQueryArgs(text(md.args))}`
682
+ : staffAttachmentArgs(rec) ?? operatorWriteArgs(rec) ?? text(md.args), SUMMARY_CAPS.args, 'args', cut),
628
683
  usage: capText(text(compactUsage(rec, true)), SUMMARY_CAPS.usage, 'usage', cut),
629
684
  reachable: reason === null,
630
685
  why_not: reason,
@@ -747,7 +802,7 @@ export function buildRead(ctx) {
747
802
  }
748
803
  catch (err) {
749
804
  releaseClientOnError(ctx, err);
750
- return { ok: false, operation: item.operation, error: typedErrorPayload(err, ctx.correlationId, requestSecrets(ctx)) };
805
+ return { ok: false, operation: item.operation, error: typedErrorPayload(err, ctx.correlationId, requestSecrets(ctx), isDirectIdentity(ctx)) };
751
806
  }
752
807
  }));
753
808
  // A cancelled request answers the typed cancellation for the WHOLE call.
@@ -14,13 +14,13 @@ export declare const MAX_REASON_DETAIL = 500;
14
14
  /**
15
15
  * How one typed error payload (the `typedErrorPayload` shape) maps onto the envelope. `next` is the SDK's
16
16
  * `nextAction` (node-autotask #296, issue #254), computed with the SDK's own `nextActionFor` for a payload
17
- * that does not carry one; the server overrides it only for its own inputs: a credential refusal stops (the
18
- * caller cannot fix the deployment's credential), and a refused cursor the caller passed (dispatch marks
19
- * `callerInput`) is caller input. The reason code is this server's closed vocabulary.
17
+ * that does not carry one. Credential and staff-permission refusals stop. A refused cursor the caller
18
+ * passed (dispatch marks `callerInput`) is caller input. The reason code is this server's closed vocabulary.
20
19
  */
21
20
  export declare function classifyError(payload: {
22
21
  code?: unknown;
23
22
  category?: unknown;
23
+ operation?: unknown;
24
24
  retryable?: unknown;
25
25
  httpStatus?: unknown;
26
26
  callerInput?: unknown;