iit-mcp-autotask 0.64.1 → 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 +19 -13
- package/capabilities.json +2 -2
- package/dist/tools/catalog-data.d.ts +12 -1
- package/dist/tools/catalog-data.js +22 -1
- package/dist/tools/context/client.js +20 -5
- package/dist/tools/context/derive.d.ts +8 -0
- package/dist/tools/context/derive.js +52 -3
- package/dist/tools/context/scope.js +2 -1
- package/dist/tools/dispatch.js +21 -7
- package/dist/tools/lists.js +9 -6
- package/dist/tools/meta.js +59 -4
- package/dist/tools/reasons.d.ts +3 -3
- package/dist/tools/reasons.js +8 -6
- package/dist/tools/results/errors.d.ts +4 -4
- package/dist/tools/results/errors.js +37 -12
- package/dist/tools/scope-guard.js +7 -2
- package/dist/tools/write/impersonation.js +2 -2
- package/package.json +2 -2
- package/server.json +2 -2
- package/skills/filter-semantics.md +9 -3
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 |
|
|
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`)
|
|
719
|
-
|
|
720
|
-
|
|
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.
|
|
726
|
-
impersonation-scope `403`
|
|
727
|
-
|
|
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`
|
|
740
|
-
|
|
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)
|
|
754
|
-
|
|
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**
|
|
757
|
-
|
|
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,
|
|
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":
|
|
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": {}
|
|
@@ -66,6 +66,17 @@ export declare function canonicalResolverResource(resource: string): string | un
|
|
|
66
66
|
export declare const TOOL_NAME_BY_OP: Readonly<Record<string, string>>;
|
|
67
67
|
/** The tool that serves one registry key: the table above, else `autotask_query` for any `<resource>.query` read (#228). */
|
|
68
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;
|
|
69
80
|
/** The served tool for this row's operation in a deployment serving `served`, or `null`. */
|
|
70
81
|
export declare function servedToolName(row: CatalogRow, served: ReadonlySet<string>): string | null;
|
|
71
82
|
/** The registry keys projected onto an MCP tool name (the reverse of {@link TOOL_NAME_BY_OP}); empty when none. */
|
|
@@ -110,7 +121,7 @@ export declare function sdkCacheOptions(cache: 'on' | 'off'): Pick<AutotaskConfi
|
|
|
110
121
|
* fails the boot (or the CI test) instead of quietly shipping a tool surface that no longer
|
|
111
122
|
* describes the SDK behind it.
|
|
112
123
|
*/
|
|
113
|
-
export declare const BUILT_AGAINST_PLAN_HASH = "
|
|
124
|
+
export declare const BUILT_AGAINST_PLAN_HASH = "51888554f455b96e13c50591342fa516b095065762430b783201ac7a995a0901";
|
|
114
125
|
/**
|
|
115
126
|
* Fail fast when the installed SDK's plan has moved out from under this surface.
|
|
116
127
|
* Called at boot (main.ts) and safe to call repeatedly (pure comparison).
|
|
@@ -104,6 +104,27 @@ export const TOOL_NAME_BY_OP = {
|
|
|
104
104
|
export function toolForOp(operation) {
|
|
105
105
|
return TOOL_NAME_BY_OP[operation] ?? (operation.endsWith('.query') && recordById(operation)?.effect === 'read' ? 'autotask_query' : undefined);
|
|
106
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
|
+
}
|
|
107
128
|
/** The served tool for this row's operation in a deployment serving `served`, or `null`. */
|
|
108
129
|
export function servedToolName(row, served) {
|
|
109
130
|
const tool = toolForOp(row.operation) ?? (row.effect === 'read' ? undefined : 'autotask_write');
|
|
@@ -201,7 +222,7 @@ export function sdkCacheOptions(cache) {
|
|
|
201
222
|
* fails the boot (or the CI test) instead of quietly shipping a tool surface that no longer
|
|
202
223
|
* describes the SDK behind it.
|
|
203
224
|
*/
|
|
204
|
-
export const BUILT_AGAINST_PLAN_HASH = '
|
|
225
|
+
export const BUILT_AGAINST_PLAN_HASH = '51888554f455b96e13c50591342fa516b095065762430b783201ac7a995a0901';
|
|
205
226
|
/**
|
|
206
227
|
* Fail fast when the installed SDK's plan has moved out from under this surface.
|
|
207
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 =
|
|
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
|
|
177
|
+
const client = getPooledClient(pool, poolConfig, log);
|
|
177
178
|
captureReadRuntime(client);
|
|
178
179
|
return { client, origin: baseNormalized.origin, poolConfig };
|
|
179
180
|
},
|
package/dist/tools/dispatch.js
CHANGED
|
@@ -11,12 +11,12 @@
|
|
|
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';
|
|
19
|
+
import { isDirectIdentity, releaseClientOnError } from './context/derive.js';
|
|
20
20
|
import { abortedResult, closedArgsError, errorContent, isShapeOnlyVendorOperation, refusalContent, resolveFaultCode, statusBasedVendorCode } from './results/errors.js';
|
|
21
21
|
import { isFileOperation, markFilePayload, markReadResult, markResult, markServerField } from './results/untrusted.js';
|
|
22
22
|
import { mirrorEnvelope } from './results/envelope.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,11 @@ 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 (
|
|
186
|
-
//
|
|
187
|
-
|
|
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;
|
|
188
193
|
}
|
|
189
194
|
}
|
|
190
195
|
}
|
|
@@ -288,6 +293,15 @@ export async function readOneItem(ctx, operation, args, signal, opts, projectRaw
|
|
|
288
293
|
});
|
|
289
294
|
if (result === undefined)
|
|
290
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
|
+
}
|
|
291
305
|
// Raw evidence must precede deepMarkUntrusted, which replaces excessively nested values.
|
|
292
306
|
if (projectRaw !== undefined)
|
|
293
307
|
return { result: projectRaw(result), ...(scopeNote !== undefined ? { scopeNote } : {}) };
|
package/dist/tools/lists.js
CHANGED
|
@@ -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
|
|
64
|
-
|
|
65
|
-
:
|
|
66
|
-
|
|
67
|
-
|
|
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
|
package/dist/tools/meta.js
CHANGED
|
@@ -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(
|
|
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.
|
package/dist/tools/reasons.d.ts
CHANGED
|
@@ -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
|
|
18
|
-
*
|
|
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;
|
package/dist/tools/reasons.js
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
* The lists are pinned by a test: adding a value is a contract change.
|
|
9
9
|
*/
|
|
10
10
|
import { nextActionFor } from 'node-autotask';
|
|
11
|
+
import { isStaffReadPermissionRefusal } from './catalog-data.js';
|
|
11
12
|
export const STATUSES = ['ok', 'needs_input', 'ambiguous', 'denied', 'error'];
|
|
12
13
|
export const NEXT_ACTIONS = [
|
|
13
14
|
'proceed',
|
|
@@ -97,20 +98,21 @@ const REASON_BY_CODE = {
|
|
|
97
98
|
/**
|
|
98
99
|
* How one typed error payload (the `typedErrorPayload` shape) maps onto the envelope. `next` is the SDK's
|
|
99
100
|
* `nextAction` (node-autotask #296, issue #254), computed with the SDK's own `nextActionFor` for a payload
|
|
100
|
-
* that does not carry one
|
|
101
|
-
*
|
|
102
|
-
* `callerInput`) is caller input. The reason code is this server's closed vocabulary.
|
|
101
|
+
* that does not carry one. Credential and staff-permission refusals stop. A refused cursor the caller
|
|
102
|
+
* passed (dispatch marks `callerInput`) is caller input. The reason code is this server's closed vocabulary.
|
|
103
103
|
*/
|
|
104
104
|
export function classifyError(payload) {
|
|
105
105
|
const code = typeof payload.code === 'string' ? payload.code : 'INTERNAL_ERROR';
|
|
106
106
|
const category = typeof payload.category === 'string' ? payload.category : undefined;
|
|
107
107
|
const callerCursor = code === 'RESPONSE_REJECTED' && payload.callerInput === true;
|
|
108
108
|
const upstream = typeof payload.httpStatus === 'number' || category === 'network' || category === 'server';
|
|
109
|
-
const
|
|
110
|
-
|
|
109
|
+
const staffPermissionRefusal = isStaffReadPermissionRefusal(payload);
|
|
110
|
+
const reason = staffPermissionRefusal ? 'UPSTREAM_ERROR' :
|
|
111
|
+
REASON_BY_CODE[code] ??
|
|
112
|
+
(category === 'not_found' ? 'TARGET_NOT_FOUND' : category === 'validation' || callerCursor ? 'INPUT_INVALID' : upstream || code !== 'INTERNAL_ERROR' ? 'UPSTREAM_ERROR' : 'INTERNAL_ERROR');
|
|
111
113
|
// a payload without a category (not an SDK error) whose code names caller input is computed as validation
|
|
112
114
|
const fallbackCategory = category ?? (reason === 'INPUT_INVALID' || reason === 'TARGET_NOT_FOUND' ? 'validation' : undefined);
|
|
113
|
-
const next = code.startsWith('CREDENTIAL_')
|
|
115
|
+
const next = staffPermissionRefusal || code.startsWith('CREDENTIAL_')
|
|
114
116
|
? 'stop'
|
|
115
117
|
: callerCursor
|
|
116
118
|
? 'supply_input'
|
|
@@ -124,9 +124,9 @@ export declare function vendorShapeDiagnostic(err: unknown, secrets: readonly st
|
|
|
124
124
|
* True when the SDK error is an upstream credential refusal (401/403-class). The typed status
|
|
125
125
|
* decides: the SDK keeps a machine-shaped vendor code (e.g. `AUTH_401`) in place of
|
|
126
126
|
* UNAUTHORIZED/FORBIDDEN, so the code alone does not. Category `auth` keeps a policy 403
|
|
127
|
-
* (HOST_POLICY_DENIED) out.
|
|
127
|
+
* (HOST_POLICY_DENIED) out. A 403 on a registered staff read can instead be an entity permission refusal.
|
|
128
128
|
*/
|
|
129
|
-
export declare function isAuthFailure(err: unknown): boolean;
|
|
129
|
+
export declare function isAuthFailure(err: unknown, directIdentity?: boolean): boolean;
|
|
130
130
|
export declare function isKnowledgeBaseRootOperation(operation: string | undefined): boolean;
|
|
131
131
|
export declare function isShapeOnlyVendorOperation(operation: string | undefined): boolean;
|
|
132
132
|
/** A vendor failure's canonical status code, also used in transport audit logs. */
|
|
@@ -156,11 +156,11 @@ export declare function shapeOnlyVendorCode(operation: string | undefined, httpS
|
|
|
156
156
|
* slot of the batched read (issue #15: a refused or failing item rides the SAME envelope in its
|
|
157
157
|
* own slot — the batch never invents its own error shape).
|
|
158
158
|
*/
|
|
159
|
-
export declare function typedErrorPayload(err: unknown, correlationId?: string, secrets?: readonly string[]): Record<string, unknown>;
|
|
159
|
+
export declare function typedErrorPayload(err: unknown, correlationId?: string, secrets?: readonly string[], directIdentity?: boolean): Record<string, unknown>;
|
|
160
160
|
/** The tool-level error envelope: the typed payload as the text block (the batch's per-item
|
|
161
161
|
* slot — issue #15 — rides the SAME payload object, so a slot error is exactly what the single
|
|
162
162
|
* read would have served). */
|
|
163
|
-
export declare function errorContent(err: unknown, correlationId?: string, secrets?: readonly string[]): ToolReturn;
|
|
163
|
+
export declare function errorContent(err: unknown, correlationId?: string, secrets?: readonly string[], directIdentity?: boolean): ToolReturn;
|
|
164
164
|
/** The kinds of a server-side fail-closed refusal (the placeholder clients, see `context/scope.ts`). */
|
|
165
165
|
export type RefusalKind = 'no_credential' | 'partial_credential' | 'no_origin' | 'bad_origin' | 'origin_not_allowed' | 'malformed_credential';
|
|
166
166
|
/** The fixed, value-free message per refusal kind (never carries a part of the refused value). */
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/** Error mapping and secret scrubbing: typed error payloads, bounded vendor errors, refusals and aborted results (issue #90). */
|
|
2
|
-
import { credentialShapeProblem, errorFromStatus, isAutotaskError, MaintenanceError, NotFoundError } from 'node-autotask';
|
|
2
|
+
import { credentialShapeProblem, errorFromStatus, isAutotaskError, MaintenanceError, NotFoundError, ResponseRejectedError } from 'node-autotask';
|
|
3
3
|
import { CREDENTIAL_LOAD_HINT } from '../../credential.js';
|
|
4
4
|
import { unknownKeysRefusal } from 'node-autotask/operations';
|
|
5
5
|
import { errorEnvelope, TRUNCATION_MARKER } from './envelope.js';
|
|
6
|
-
import { canonicalResolverResource } from '../catalog-data.js';
|
|
6
|
+
import { canonicalResolverResource, isStaffReadOperation, isStaffReadPermissionRefusal } from '../catalog-data.js';
|
|
7
7
|
import { classifyError } from '../reasons.js';
|
|
8
8
|
import { UNTRUSTED_CLOSE, UNTRUSTED_OPEN } from 'node-autotask/untrusted';
|
|
9
9
|
import { cleanUntrustedText, EVERY_ITEM, LONG_TEXT_CAP, note, stripUnsafeChars, wrapOrSelf } from './untrusted.js';
|
|
@@ -291,12 +291,14 @@ export function vendorShapeDiagnostic(err, secrets) {
|
|
|
291
291
|
* True when the SDK error is an upstream credential refusal (401/403-class). The typed status
|
|
292
292
|
* decides: the SDK keeps a machine-shaped vendor code (e.g. `AUTH_401`) in place of
|
|
293
293
|
* UNAUTHORIZED/FORBIDDEN, so the code alone does not. Category `auth` keeps a policy 403
|
|
294
|
-
* (HOST_POLICY_DENIED) out.
|
|
294
|
+
* (HOST_POLICY_DENIED) out. A 403 on a registered staff read can instead be an entity permission refusal.
|
|
295
295
|
*/
|
|
296
|
-
export function isAuthFailure(err) {
|
|
296
|
+
export function isAuthFailure(err, directIdentity = false) {
|
|
297
297
|
if (err instanceof MaintenanceError)
|
|
298
298
|
return false;
|
|
299
299
|
const e = err;
|
|
300
|
+
if (directIdentity && e && isStaffReadPermissionRefusal(e))
|
|
301
|
+
return false;
|
|
300
302
|
const code = e?.code;
|
|
301
303
|
return (((e?.httpStatus === 401 || e?.httpStatus === 403) && e.category === 'auth') ||
|
|
302
304
|
(typeof code === 'string' && (code === 'UNAUTHORIZED' || code === 'FORBIDDEN')) ||
|
|
@@ -308,7 +310,7 @@ export function isKnowledgeBaseRootOperation(operation) {
|
|
|
308
310
|
}
|
|
309
311
|
export function isShapeOnlyVendorOperation(operation) {
|
|
310
312
|
return operation !== undefined && (isKnowledgeBaseRootOperation(operation)
|
|
311
|
-
|| /^(inventory_items|inventory_locations|internal_locations|shipping_types)\./.test(operation)
|
|
313
|
+
|| /^(inventory_items|inventory_locations|internal_locations|shipping_types|organizational_resources|resource_daily_availabilities)\./.test(operation)
|
|
312
314
|
|| /^products\.(get|fetchRecord|fetchByIds)$/.test(operation));
|
|
313
315
|
}
|
|
314
316
|
/** A vendor failure's canonical status code, also used in transport audit logs. */
|
|
@@ -326,11 +328,21 @@ export function resolveFaultCode(resource, error) {
|
|
|
326
328
|
}
|
|
327
329
|
/** Strip vendor-supplied codes while preserving trusted SDK envelope and maintenance classifications. */
|
|
328
330
|
export function shapeOnlyVendorCode(operation, httpStatus, error) {
|
|
331
|
+
if (!isShapeOnlyVendorOperation(operation))
|
|
332
|
+
return undefined;
|
|
333
|
+
const staffRead = isStaffReadOperation(operation);
|
|
334
|
+
if (staffRead && error instanceof ResponseRejectedError)
|
|
335
|
+
return error.code;
|
|
329
336
|
const vendorError = error?.vendorError;
|
|
330
|
-
if (
|
|
337
|
+
if (httpStatus === undefined && vendorError === undefined)
|
|
331
338
|
return undefined;
|
|
332
339
|
if (error instanceof MaintenanceError)
|
|
333
340
|
return 'MAINTENANCE';
|
|
341
|
+
// An auth-looking response status can be attached to an SDK response-policy rejection.
|
|
342
|
+
if (staffRead && (httpStatus === 401 || httpStatus === 403) &&
|
|
343
|
+
(!isAutotaskError(error) || error.category !== 'auth')) {
|
|
344
|
+
return 'AUTOTASK_ERROR';
|
|
345
|
+
}
|
|
334
346
|
return statusBasedVendorCode(operation, httpStatus)
|
|
335
347
|
?? (vendorError === undefined && isAutotaskError(error) ? error.code : 'AUTOTASK_ERROR');
|
|
336
348
|
}
|
|
@@ -355,7 +367,7 @@ export function shapeOnlyVendorCode(operation, httpStatus, error) {
|
|
|
355
367
|
* slot of the batched read (issue #15: a refused or failing item rides the SAME envelope in its
|
|
356
368
|
* own slot — the batch never invents its own error shape).
|
|
357
369
|
*/
|
|
358
|
-
export function typedErrorPayload(err, correlationId, secrets = []) {
|
|
370
|
+
export function typedErrorPayload(err, correlationId, secrets = [], directIdentity = false) {
|
|
359
371
|
const e = (typeof err === 'object' && err !== null ? err : {});
|
|
360
372
|
const str = (v) => (typeof v === 'string' && v.length > 0 ? v : undefined);
|
|
361
373
|
const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : undefined);
|
|
@@ -368,8 +380,9 @@ export function typedErrorPayload(err, correlationId, secrets = []) {
|
|
|
368
380
|
&& httpStatus === 200 && e.vendorError === undefined;
|
|
369
381
|
const authFailure = shapeOnlyVendorError
|
|
370
382
|
? vendorCode === 'UNAUTHORIZED' || vendorCode === 'FORBIDDEN'
|
|
371
|
-
: isAuthFailure(err);
|
|
372
|
-
|
|
383
|
+
: isAuthFailure(err, directIdentity);
|
|
384
|
+
const staffPermissionRefusal = directIdentity && isStaffReadPermissionRefusal(e);
|
|
385
|
+
if (authFailure && !staffPermissionRefusal)
|
|
373
386
|
return unauthorizedPayload(correlationId, vendorShapeDiagnostic(err, secrets));
|
|
374
387
|
const code = vendorCode ?? str(e.code) ?? (isAutotaskError(err) ? 'AUTOTASK_ERROR' : undefined) ?? 'INTERNAL_ERROR';
|
|
375
388
|
const url = str(e.url);
|
|
@@ -402,6 +415,14 @@ export function typedErrorPayload(err, correlationId, secrets = []) {
|
|
|
402
415
|
? 'No inventory location was visible to this API user at the requested ID.'
|
|
403
416
|
: 'No record was visible to this API user at the requested ID.';
|
|
404
417
|
}
|
|
418
|
+
else if (staffPermissionRefusal) {
|
|
419
|
+
payload.message = 'Autotask refused permission for this staff read (HTTP 403).';
|
|
420
|
+
}
|
|
421
|
+
else if (isStaffReadOperation(operation) && err instanceof ResponseRejectedError) {
|
|
422
|
+
payload.message = code === 'RESPONSE_TOO_LARGE' ? 'The Autotask response exceeded the SDK response size limit.'
|
|
423
|
+
: code === 'REDIRECT_BLOCKED' ? 'The SDK blocked an Autotask response redirect.'
|
|
424
|
+
: 'The SDK rejected the Autotask response under its response policy.';
|
|
425
|
+
}
|
|
405
426
|
else if (httpStatus !== undefined) {
|
|
406
427
|
payload.message = shapeMessage(httpStatus, url);
|
|
407
428
|
}
|
|
@@ -421,8 +442,12 @@ export function typedErrorPayload(err, correlationId, secrets = []) {
|
|
|
421
442
|
if (sdkValidation)
|
|
422
443
|
note(payload, 'message', 'long');
|
|
423
444
|
const suggestedAction = str(e.suggestedAction);
|
|
424
|
-
if (
|
|
445
|
+
if (staffPermissionRefusal) {
|
|
446
|
+
payload.suggestedAction = "Have an Autotask administrator verify the API user's permissions and feature activation before retrying.";
|
|
447
|
+
}
|
|
448
|
+
else if (!shapeOnlyVendorError && suggestedAction !== undefined) {
|
|
425
449
|
payload.suggestedAction = stripThenScrub(suggestedAction, secrets);
|
|
450
|
+
}
|
|
426
451
|
// SDK-built budget guidance contains no vendor text; preserve its complete narrowing options.
|
|
427
452
|
if (rollupBudget)
|
|
428
453
|
for (const key of ['message', 'suggestedAction'])
|
|
@@ -476,8 +501,8 @@ function boundedMessage(raw, keepWhole, url, secrets) {
|
|
|
476
501
|
/** The tool-level error envelope: the typed payload as the text block (the batch's per-item
|
|
477
502
|
* slot — issue #15 — rides the SAME payload object, so a slot error is exactly what the single
|
|
478
503
|
* read would have served). */
|
|
479
|
-
export function errorContent(err, correlationId = '', secrets = []) {
|
|
480
|
-
const payload = typedErrorPayload(err, correlationId, secrets);
|
|
504
|
+
export function errorContent(err, correlationId = '', secrets = [], directIdentity = false) {
|
|
505
|
+
const payload = typedErrorPayload(err, correlationId, secrets, directIdentity);
|
|
481
506
|
const field = err?.field;
|
|
482
507
|
return errorEnvelope(payload, String(payload.correlationId ?? correlationId), typeof field === 'string' ? field : undefined);
|
|
483
508
|
}
|
|
@@ -1,11 +1,16 @@
|
|
|
1
|
-
import { isDeletedActivityAuditResource } from './catalog-data.js';
|
|
1
|
+
import { isDeletedActivityAuditResource, staffReadParentFilter } from './catalog-data.js';
|
|
2
2
|
/** Map the SDK scope refusal to the calling tool's input spelling and supported fields. */
|
|
3
3
|
export function scopeRequiredInput(err, field, snakeCase = false) {
|
|
4
4
|
if (err === null || typeof err !== 'object' || err.code !== 'SCOPE_REQUIRED')
|
|
5
5
|
return err;
|
|
6
6
|
const e = err;
|
|
7
7
|
e.field = field;
|
|
8
|
-
|
|
8
|
+
const resource = typeof e.operation === 'string' ? e.operation.split('.', 1)[0] ?? '' : '';
|
|
9
|
+
const parentField = staffReadParentFilter(resource);
|
|
10
|
+
if (parentField !== undefined) {
|
|
11
|
+
e.suggestedAction = `Filter on ${parentField} or the row id with eq or in, or use count for totals. For an intentional broad walk, pass acknowledgeUnscoped: true.`;
|
|
12
|
+
}
|
|
13
|
+
else if (isDeletedActivityAuditResource(resource)) {
|
|
9
14
|
e.suggestedAction = 'Filter on the audit log id with eq or in, or use count for totals. For an intentional broad walk, pass acknowledgeUnscoped: true.';
|
|
10
15
|
}
|
|
11
16
|
if (snakeCase && typeof e.suggestedAction === 'string')
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { assertOperationPermitted } from '../../policy.js';
|
|
3
3
|
import { abortedResult } from '../results/errors.js';
|
|
4
4
|
import { captureReadRuntime } from '../read-runtime.js';
|
|
5
|
-
import { releaseClientOnError } from '../context/derive.js';
|
|
5
|
+
import { getPooledClient, releaseClientOnError } from '../context/derive.js';
|
|
6
6
|
import { answer, reason } from './common.js';
|
|
7
7
|
export function impersonatedContext(ctx, id) {
|
|
8
8
|
if (id === undefined)
|
|
@@ -10,7 +10,7 @@ export function impersonatedContext(ctx, id) {
|
|
|
10
10
|
if (ctx.pool === undefined || ctx.poolConfig === undefined)
|
|
11
11
|
throw new Error('write impersonation needs a resolved SDK client pool');
|
|
12
12
|
const poolConfig = { ...ctx.poolConfig, impersonationResourceId: String(id) };
|
|
13
|
-
const client = ctx.pool.
|
|
13
|
+
const client = getPooledClient(ctx.pool, poolConfig, ctx.log);
|
|
14
14
|
captureReadRuntime(client);
|
|
15
15
|
return { ...ctx, client, poolConfig };
|
|
16
16
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "iit-mcp-autotask",
|
|
3
|
-
"version": "0.64.
|
|
3
|
+
"version": "0.64.2",
|
|
4
4
|
"description": "MCP server for the Autotask (Datto) PSA domain, built on the node-autotask SDK",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Max Soukhomlinov",
|
|
@@ -54,7 +54,7 @@
|
|
|
54
54
|
},
|
|
55
55
|
"dependencies": {
|
|
56
56
|
"@modelcontextprotocol/server": "^2.2.0",
|
|
57
|
-
"node-autotask": "0.
|
|
57
|
+
"node-autotask": "0.93.1",
|
|
58
58
|
"zod": "^4.6.7"
|
|
59
59
|
},
|
|
60
60
|
"devDependencies": {
|
package/server.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "iit-mcp-autotask",
|
|
3
|
-
"version": "0.64.
|
|
3
|
+
"version": "0.64.2",
|
|
4
4
|
"description": "MCP server for the Autotask (Datto) PSA API, powered by the node-autotask SDK",
|
|
5
5
|
"mcpProtocolBaseline": "2026-07-28",
|
|
6
6
|
"legacyProtocolFallback": "2025-11-25",
|
|
@@ -62,7 +62,7 @@
|
|
|
62
62
|
"capabilitiesManifest": "capabilities.json",
|
|
63
63
|
"sdk": {
|
|
64
64
|
"package": "node-autotask",
|
|
65
|
-
"versionRange": "0.
|
|
65
|
+
"versionRange": "0.93.1"
|
|
66
66
|
},
|
|
67
67
|
"vendorExtensions": false,
|
|
68
68
|
"credentialModelNote": "per-request; server-held under stdio or, on HTTP, only behind AUTOTASK_HTTP_AUTH=tokens; operator plans and the ledger are keyed by principal and tenant id, never by credential, and an apply authenticates the request credential and restores the plan's per-write impersonation"
|
|
@@ -5,7 +5,7 @@ version: 1
|
|
|
5
5
|
profile: readonly
|
|
6
6
|
description: Filter footguns for autotask_query: strict date lt, case-insensitive contains, FK 0 vs NULL, field-name checks, all-strings values.
|
|
7
7
|
when_not_to_use: the filter grammar itself (the 13 operators + and/or grouping, server instructions); the per-operation notes (autotask_describe)
|
|
8
|
-
ops: ["autotask_query:tickets.query", "autotask_query:time_entries.query", "autotask_query:service_calls.query", "autotask_query:contracts.query", "autotask_query:time_off_requests.query", "autotask_read:operations.fieldCatalog", "autotask_resource_workload", "autotask_query:operations.aggregate"]
|
|
8
|
+
ops: ["autotask_query:tickets.query", "autotask_query:time_entries.query", "autotask_query:service_calls.query", "autotask_query:contracts.query", "autotask_query:time_off_requests.query", "autotask_read:operations.fieldCatalog", "autotask_resource_workload", "autotask_query:operations.aggregate", "autotask_query:organizational_resources.query", "autotask_query:resource_daily_availabilities.query", "autotask_read:organizational_resources.listByParent", "autotask_read:resource_daily_availabilities.listByParent"]
|
|
9
9
|
inputs: {"type": "object", "required": [], "properties": {}}
|
|
10
10
|
outcomes: ["ok", "error"]
|
|
11
11
|
hazards: ["gt/lt around a day boundary silently drops an edge day", "ticketID eq 0 finds nothing (time_entries store NULL)", "an unknown field name is a zero-query-wire CONFIG_ERROR (0.20.0 pre-validation; a cold field cache makes one vendor metadata GET first)"]
|
|
@@ -28,10 +28,12 @@ No inputs: this is a reference page about the filter behaviour of autotask_query
|
|
|
28
28
|
3. tickets.search is a vendor contains on the TITLE only: no free-text search, no matched-field reporting, and vendor contains is looser than a literal substring (case/token matching can return MORE hits than a local title-substring check). The per-field contains of tickets.query is the precise tool.
|
|
29
29
|
4. Unassigned FKs are not uniform. tickets store 0; time_entries store NULL. Unallocated time needs notExist (ticketID eq 0 finds nothing); assignedResourceID eq 0 and notExist differ.
|
|
30
30
|
5. Field names are vendor casing, and an unknown field name fails pre-dispatch as a typed CONFIG_ERROR with the field-catalog pointer and zero query wire, on every autotask_query resource (totals: group_by and sum too). One udf: true condition per query is exempt from the name check. List names for the queried resource with the scoped call `autotask_read {operation:"operations.fieldCatalog", args:[{resources:["<resource>"]}]}` (add `fields: [names]` to project, `labels: true`; never `<resource>.getFieldInfo`). Never the bare `operations.fieldCatalog`: it serves a capped five-resource catalog (~87 KB) and has no row for time_entries, service_calls, contracts or time_off_requests. Do not guess names. The answer is `data.results[0].result`.
|
|
31
|
-
6. Some clients (Copilot Studio)
|
|
32
|
-
7. tickets.assignedResourceID
|
|
31
|
+
6. Some clients (Copilot Studio) reject arrays mixing strings and other value types. Send filter values as strings. The server and SDK pass them through unchanged. String dates, IDs and booleans are confirmed on resources and time_entries. For scoped time rows without posted counts, use `autotask_query {resource:"time_entries", filter:[{field:"resourceID",op:"eq",value:"<resource id>"},{field:"dateWorked",op:"gte",value:"2026-10-20"},{field:"dateWorked",op:"lte",value:"2026-10-22"}], limit:500}`. For an unscoped window use `autotask_read {operation:"time_entries.dateWorkedWindow", args:["2026-10-20","2026-10-22"]}`. It returns one page and exposes `nextCursor` for the next call. A query defaults to 50 rows.
|
|
32
|
+
7. `tickets.assignedResourceID` covers primary owners. `ticket_secondary_resources` links secondary staff and has no status. Use `autotask_resource_workload {id}` for deduplicated open tickets across both tables. Quote `totals`, with `totals.capped` indicating a lower bound. `counts` covers returned rows. If `totalsAbsent` is set, report the totals unavailable and keep the rows. If `value.capped` is true, increase `ticket_limit` up to 500 and disclose any remaining truncation. `CLOSED_STATUS_UNRESOLVED` means the count is unavailable.
|
|
33
33
|
8. Scope every `*.query` by ids (`eq`/`in` on `*ID`): unscoped is a tenant-wide walk, refused above 500 rows unless `acknowledge_unscoped` (query) or `acknowledgeUnscoped` (read). Totals: `autotask_query` `group_by`/`sum`/`count`. Time entries: scope by `ticket.companyID`.
|
|
34
34
|
|
|
35
|
+
Filter `organizational_resources` on `organizationalLevelAssociationID` and `resource_daily_availabilities` on `resourceID`. Use `autotask_read` with `organizational_resources.listByParent` or `resource_daily_availabilities.listByParent` and `[parentId]` for one native page with `hasMore` and no cursor. Native and global visibility may differ. An empty response is inconclusive. Neither parent establishes company ownership.
|
|
36
|
+
|
|
35
37
|
## Guardrails
|
|
36
38
|
|
|
37
39
|
- Apply the 8 rules when composing or debugging any autotask_query filter.
|
|
@@ -72,4 +74,8 @@ No inputs: this is a reference page about the filter behaviour of autotask_query
|
|
|
72
74
|
| autotask_read | operations.fieldCatalog | read | - |
|
|
73
75
|
| autotask_resource_workload | - | - | - |
|
|
74
76
|
| autotask_query | operations.aggregate | read | operation, filter |
|
|
77
|
+
| autotask_query | organizational_resources.query | read | - |
|
|
78
|
+
| autotask_query | resource_daily_availabilities.query | read | - |
|
|
79
|
+
| autotask_read | organizational_resources.listByParent | read | parentId |
|
|
80
|
+
| autotask_read | resource_daily_availabilities.listByParent | read | parentId |
|
|
75
81
|
<!-- generated:end -->
|