iit-mcp-autotask 0.64.1 → 0.65.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -13
- package/capabilities.json +2 -2
- package/dist/tools/catalog-data.d.ts +13 -1
- package/dist/tools/catalog-data.js +27 -1
- package/dist/tools/context/client.js +27 -6
- package/dist/tools/context/derive.d.ts +12 -0
- package/dist/tools/context/derive.js +95 -3
- package/dist/tools/context/scope.js +2 -1
- package/dist/tools/context/types.d.ts +3 -1
- package/dist/tools/dispatch.d.ts +2 -0
- package/dist/tools/dispatch.js +26 -10
- package/dist/tools/lists.js +11 -6
- package/dist/tools/meta.js +62 -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 +39 -12
- package/dist/tools/scope-guard.js +7 -2
- package/dist/tools/write/apply.js +128 -56
- package/dist/tools/write/impersonation.js +8 -14
- package/dist/tools/write/outcome.js +31 -4
- package/dist/tools/write/preview.js +8 -9
- package/dist/tools/write/snapshot.d.ts +9 -2
- package/dist/tools/write/snapshot.js +159 -12
- 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,444 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": 1444,
|
|
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,18 @@ 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
|
+
/** A direct HTTP 403 on these reads can be an entity permission refusal. */
|
|
75
|
+
export declare function isEntityReadPermissionRefusal(error: {
|
|
76
|
+
operation?: unknown;
|
|
77
|
+
httpStatus?: unknown;
|
|
78
|
+
category?: unknown;
|
|
79
|
+
}): boolean;
|
|
80
|
+
export declare function isDocumentCategoryReadOperation(operation: unknown): boolean;
|
|
69
81
|
/** The served tool for this row's operation in a deployment serving `served`, or `null`. */
|
|
70
82
|
export declare function servedToolName(row: CatalogRow, served: ReadonlySet<string>): string | null;
|
|
71
83
|
/** The registry keys projected onto an MCP tool name (the reverse of {@link TOOL_NAME_BY_OP}); empty when none. */
|
|
@@ -110,7 +122,7 @@ export declare function sdkCacheOptions(cache: 'on' | 'off'): Pick<AutotaskConfi
|
|
|
110
122
|
* fails the boot (or the CI test) instead of quietly shipping a tool surface that no longer
|
|
111
123
|
* describes the SDK behind it.
|
|
112
124
|
*/
|
|
113
|
-
export declare const BUILT_AGAINST_PLAN_HASH = "
|
|
125
|
+
export declare const BUILT_AGAINST_PLAN_HASH = "86416d6a76ecf010aa7956b6910b253de22ddabec45711f79dd4aeaa38c0466e";
|
|
114
126
|
/**
|
|
115
127
|
* Fail fast when the installed SDK's plan has moved out from under this surface.
|
|
116
128
|
* Called at boot (main.ts) and safe to call repeatedly (pure comparison).
|
|
@@ -104,6 +104,32 @@ 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
|
+
/** A direct HTTP 403 on these reads can be an entity permission refusal. */
|
|
125
|
+
export function isEntityReadPermissionRefusal(error) {
|
|
126
|
+
return error.httpStatus === 403 && error.category === 'auth'
|
|
127
|
+
&& (isStaffReadOperation(error.operation) || isDocumentCategoryReadOperation(error.operation));
|
|
128
|
+
}
|
|
129
|
+
export function isDocumentCategoryReadOperation(operation) {
|
|
130
|
+
const record = typeof operation === 'string' ? recordById(operation) : undefined;
|
|
131
|
+
return record?.effect === 'read' && record.resource === 'document_categories';
|
|
132
|
+
}
|
|
107
133
|
/** The served tool for this row's operation in a deployment serving `served`, or `null`. */
|
|
108
134
|
export function servedToolName(row, served) {
|
|
109
135
|
const tool = toolForOp(row.operation) ?? (row.effect === 'read' ? undefined : 'autotask_write');
|
|
@@ -201,7 +227,7 @@ export function sdkCacheOptions(cache) {
|
|
|
201
227
|
* fails the boot (or the CI test) instead of quietly shipping a tool surface that no longer
|
|
202
228
|
* describes the SDK behind it.
|
|
203
229
|
*/
|
|
204
|
-
export const BUILT_AGAINST_PLAN_HASH = '
|
|
230
|
+
export const BUILT_AGAINST_PLAN_HASH = '86416d6a76ecf010aa7956b6910b253de22ddabec45711f79dd4aeaa38c0466e';
|
|
205
231
|
/**
|
|
206
232
|
* Fail fast when the installed SDK's plan has moved out from under this surface.
|
|
207
233
|
* 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 { isDocumentCategoryReadOperation, 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 READ_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) || isDocumentCategoryReadOperation(operation)) {
|
|
27
|
+
// A terminal SDK failure can carry the status from an earlier retry.
|
|
28
|
+
if (READ_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 } : {}),
|
|
@@ -124,7 +139,13 @@ export function buildStdioClient(config, log) {
|
|
|
124
139
|
* `invokeRead` and its governor; `authenticate.*` is refused by the deployment policy before it.)
|
|
125
140
|
*/
|
|
126
141
|
export const defaultToolOps = {
|
|
127
|
-
invokeRead: (client, operation, args, opts, signal) => withSignal(client, signal, () =>
|
|
142
|
+
invokeRead: (client, operation, args, { freshMetadata, ...opts } = {}, signal) => withSignal(client, signal, () => {
|
|
143
|
+
const sdk = client;
|
|
144
|
+
// The SDK documents invalidation as the way to refresh a raw, no-argument metadata read.
|
|
145
|
+
if (freshMetadata === true)
|
|
146
|
+
sdk.http.fieldCache?.invalidate(`${operation.split('.')[0]}:fields`);
|
|
147
|
+
return invokeRead(sdk, operation, args, opts);
|
|
148
|
+
}),
|
|
128
149
|
invokeReadPages: (client, operation, args, onPage, opts, signal) => withSignal(client, signal, () => invokeReadPages(client, operation, args, onPage, opts ?? {})),
|
|
129
150
|
invokeWrite: (client, operation, args, opts, signal) => withSignal(client, signal, () => invokeWrite(client, operation, args, opts ?? {})),
|
|
130
151
|
invokeDelete: (client, operation, args, opts, signal) => withSignal(client, signal, () => invokeDelete(client, operation, args, opts ?? {})),
|
|
@@ -1,6 +1,18 @@
|
|
|
1
|
+
import { AutotaskClient, type AutotaskConfig, type AutotaskError } from 'node-autotask';
|
|
2
|
+
import type { ClientPool } from 'node-autotask/pool';
|
|
3
|
+
import type { Logger } from '../../logger.js';
|
|
1
4
|
import type { ToolDeps, ToolContext } from './types.js';
|
|
5
|
+
export declare function isImpersonationValidationDenial(error: unknown): error is AutotaskError & {
|
|
6
|
+
httpStatus: 401 | 403;
|
|
7
|
+
};
|
|
8
|
+
/** Scope the wire hook to the validation call, since resources.get also serves ordinary reads. */
|
|
9
|
+
export declare function withImpersonationValidation<T>(ctx: ToolContext, read: () => Promise<T>): Promise<T>;
|
|
10
|
+
/** Resolve the SDK client and bind invalidation to its exact pool key. */
|
|
11
|
+
export declare function getPooledClient(pool: ClientPool, config: AutotaskConfig, log: Logger): AutotaskClient;
|
|
2
12
|
/** Derive the context the registrations share. */
|
|
3
13
|
export declare function deriveToolContext(deps: ToolDeps, served?: ReadonlySet<string>): ToolContext;
|
|
14
|
+
/** An entity permission refusal applies only to a resolved direct identity. */
|
|
15
|
+
export declare function isDirectIdentity(deps: Pick<ToolDeps, 'poolConfig'>): boolean;
|
|
4
16
|
/**
|
|
5
17
|
* A vendor 401 (or impersonation-scope 401/403) deletes the pooled entry so a stale identity is
|
|
6
18
|
* not negative-cached and replayed (security S1/C1.8, S3/C3.5): the next request with the same
|
|
@@ -1,7 +1,87 @@
|
|
|
1
1
|
/** Deriving a tool context from the deps, and releasing a client on error (issue #91). */
|
|
2
|
-
import {
|
|
2
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
3
|
+
import { AutotaskClient, isAutotaskError } from 'node-autotask';
|
|
3
4
|
import { isAuthFailure } from '../results/errors.js';
|
|
4
|
-
import { recordById, toolDescription, untrustedFieldsOf } from '../catalog-data.js';
|
|
5
|
+
import { isDocumentCategoryReadOperation, isRegisteredMetadataRead, isStaffReadOperation, recordById, toolDescription, untrustedFieldsOf } from '../catalog-data.js';
|
|
6
|
+
// A real client with this hook handles eviction once per wire refusal, even if multiple readers share the result.
|
|
7
|
+
const auditInvalidatesCredentialReads = new WeakSet();
|
|
8
|
+
const impersonationValidation = new AsyncLocalStorage();
|
|
9
|
+
const invalidatedValidationErrors = new WeakSet();
|
|
10
|
+
function isCredentialReadDenial(operation, status, impersonated) {
|
|
11
|
+
return (status === 401 || (status === 403 && impersonated)) &&
|
|
12
|
+
(isStaffReadOperation(operation) || isRegisteredMetadataRead(operation) || isDocumentCategoryReadOperation(operation));
|
|
13
|
+
}
|
|
14
|
+
function isCategoryMutation(operation, method) {
|
|
15
|
+
return (operation === 'document_categories.create' && method === 'POST')
|
|
16
|
+
|| (operation === 'document_categories.update' && method === 'PUT')
|
|
17
|
+
|| (operation === 'document_categories.delete' && method === 'DELETE');
|
|
18
|
+
}
|
|
19
|
+
function invalidateCredentialReads(pool, config, client, log) {
|
|
20
|
+
// A pinned stdio or in-flight client can outlive its pool entry. Clear its stores if the pool did not.
|
|
21
|
+
const readCache = client?.http.readCache;
|
|
22
|
+
const fieldCache = client?.http.fieldCache;
|
|
23
|
+
const readEpoch = readCache?.epoch;
|
|
24
|
+
const fieldEpoch = fieldCache?.epoch;
|
|
25
|
+
const removed = pool.delete(config, { clearCachedReads: true });
|
|
26
|
+
if (readCache?.epoch === readEpoch)
|
|
27
|
+
readCache?.clear();
|
|
28
|
+
if (fieldCache?.epoch === fieldEpoch)
|
|
29
|
+
fieldCache?.clear();
|
|
30
|
+
if (removed)
|
|
31
|
+
log.info('deleted pooled client after credential refusal', { removed, poolSize: pool.size });
|
|
32
|
+
}
|
|
33
|
+
export function isImpersonationValidationDenial(error) {
|
|
34
|
+
return isAutotaskError(error) && error.operation === 'resources.get' && error.category === 'auth'
|
|
35
|
+
&& (error.httpStatus === 401 || error.httpStatus === 403);
|
|
36
|
+
}
|
|
37
|
+
/** Scope the wire hook to the validation call, since resources.get also serves ordinary reads. */
|
|
38
|
+
export async function withImpersonationValidation(ctx, read) {
|
|
39
|
+
const scope = { client: ctx.client, invalidated: false };
|
|
40
|
+
try {
|
|
41
|
+
return await impersonationValidation.run(scope, read);
|
|
42
|
+
}
|
|
43
|
+
catch (error) {
|
|
44
|
+
const { pool, poolConfig, client, log } = ctx;
|
|
45
|
+
if (pool !== undefined && poolConfig?.impersonationResourceId !== undefined && isImpersonationValidationDenial(error)) {
|
|
46
|
+
if (!scope.invalidated)
|
|
47
|
+
invalidateCredentialReads(pool, poolConfig, client instanceof AutotaskClient ? client : undefined, log);
|
|
48
|
+
invalidatedValidationErrors.add(error);
|
|
49
|
+
}
|
|
50
|
+
throw error;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/** Resolve the SDK client and bind invalidation to its exact pool key. */
|
|
54
|
+
export function getPooledClient(pool, config, log) {
|
|
55
|
+
const client = pool.get({
|
|
56
|
+
...config,
|
|
57
|
+
onAudit(event) {
|
|
58
|
+
const { status, operation, method, errorCode, notSent } = event;
|
|
59
|
+
// The SDK can retain a machine code containing digits for a real status error.
|
|
60
|
+
// Its own abort, maintenance and response-policy codes do not describe an auth denial.
|
|
61
|
+
const authCode = errorCode === (status === 401 ? 'UNAUTHORIZED' : 'FORBIDDEN') ||
|
|
62
|
+
(errorCode !== undefined && /^[a-z0-9][a-z0-9_-]{2,}$/i.test(errorCode) && /\d/.test(errorCode));
|
|
63
|
+
if (notSent !== true && authCode) {
|
|
64
|
+
const readDenial = isCredentialReadDenial(operation, status, config.impersonationResourceId !== undefined);
|
|
65
|
+
if (readDenial)
|
|
66
|
+
auditInvalidatesCredentialReads.add(client);
|
|
67
|
+
const validation = impersonationValidation.getStore();
|
|
68
|
+
const validationDenial = validation?.client === client && config.impersonationResourceId !== undefined
|
|
69
|
+
&& operation === 'resources.get' && method === 'GET' && (status === 401 || status === 403);
|
|
70
|
+
// The wire can settle after apply has returned an unknown outcome.
|
|
71
|
+
if (readDenial || validationDenial || (status === 401 && isCategoryMutation(operation, method))) {
|
|
72
|
+
invalidateCredentialReads(pool, config, client, log);
|
|
73
|
+
}
|
|
74
|
+
if (validationDenial) {
|
|
75
|
+
validation.invalidated = true;
|
|
76
|
+
config.onAudit?.({ ...event, errorCode: status === 401 ? 'UNAUTHORIZED' : 'FORBIDDEN' });
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
config.onAudit?.(event);
|
|
81
|
+
},
|
|
82
|
+
});
|
|
83
|
+
return client;
|
|
84
|
+
}
|
|
5
85
|
/** Derive the context the registrations share. */
|
|
6
86
|
export function deriveToolContext(deps, served = new Set()) {
|
|
7
87
|
return {
|
|
@@ -16,6 +96,10 @@ export function deriveToolContext(deps, served = new Set()) {
|
|
|
16
96
|
description: toolDescription,
|
|
17
97
|
};
|
|
18
98
|
}
|
|
99
|
+
/** An entity permission refusal applies only to a resolved direct identity. */
|
|
100
|
+
export function isDirectIdentity(deps) {
|
|
101
|
+
return deps.poolConfig !== undefined && deps.poolConfig.impersonationResourceId === undefined;
|
|
102
|
+
}
|
|
19
103
|
/**
|
|
20
104
|
* A vendor 401 (or impersonation-scope 401/403) deletes the pooled entry so a stale identity is
|
|
21
105
|
* not negative-cached and replayed (security S1/C1.8, S3/C3.5): the next request with the same
|
|
@@ -24,7 +108,15 @@ export function deriveToolContext(deps, served = new Set()) {
|
|
|
24
108
|
export function releaseClientOnError(deps, err) {
|
|
25
109
|
if (deps.pool === undefined || deps.poolConfig === undefined)
|
|
26
110
|
return;
|
|
27
|
-
if (isAutotaskError(err) && isAuthFailure(err)) {
|
|
111
|
+
if (isAutotaskError(err) && isAuthFailure(err, isDirectIdentity(deps))) {
|
|
112
|
+
if (invalidatedValidationErrors.has(err))
|
|
113
|
+
return;
|
|
114
|
+
if (err.category === 'auth' && isCredentialReadDenial(err.operation, err.httpStatus, !isDirectIdentity(deps))) {
|
|
115
|
+
if (!auditInvalidatesCredentialReads.has(deps.client)) {
|
|
116
|
+
invalidateCredentialReads(deps.pool, deps.poolConfig, deps.client instanceof AutotaskClient ? deps.client : undefined, deps.log);
|
|
117
|
+
}
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
28
120
|
const removed = deps.pool.delete(deps.poolConfig);
|
|
29
121
|
deps.log.info('deleted pooled client after credential refusal', { removed, poolSize: deps.pool.size });
|
|
30
122
|
}
|
|
@@ -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
|
},
|
|
@@ -53,7 +53,9 @@ export interface HourlyBudget {
|
|
|
53
53
|
/** The SDK operations the handler layer drives, bound in ONE place (the mock seam). */
|
|
54
54
|
export interface ToolOps {
|
|
55
55
|
/** The MCP request's AbortSignal, when the transport provides one: an abandoned request stops consuming vendor budget. */
|
|
56
|
-
invokeRead(client: ToolClient, operation: string, args?: readonly unknown[], opts?: InvokeOptions
|
|
56
|
+
invokeRead(client: ToolClient, operation: string, args?: readonly unknown[], opts?: InvokeOptions & {
|
|
57
|
+
freshMetadata?: true;
|
|
58
|
+
}, signal?: AbortSignal): Promise<unknown>;
|
|
57
59
|
invokeReadPages(client: ToolClient, operation: string, args: readonly unknown[], onPage: BoundedQueryPageConsumer, opts?: InvokeOptions, signal?: AbortSignal): Promise<BoundedQuerySummary | undefined>;
|
|
58
60
|
invokeWrite(client: ToolClient, operation: string, args?: readonly unknown[], opts?: InvokeOptions, signal?: AbortSignal): Promise<unknown>;
|
|
59
61
|
invokeDelete(client: ToolClient, operation: string, args?: readonly unknown[], opts?: InvokeOptions, signal?: AbortSignal): Promise<unknown>;
|
package/dist/tools/dispatch.d.ts
CHANGED
|
@@ -34,6 +34,8 @@ export declare class InputInvalidError extends AutotaskConfigError {
|
|
|
34
34
|
* 5. the correlation id stamped on the envelope (and the mirrored text block).
|
|
35
35
|
*/
|
|
36
36
|
export declare function runTool<A = Record<string, unknown>>(ctx: ToolContext, input: ClosedInput, rawArgs: unknown, extra: unknown, work: (args: A, signal: AbortSignal | undefined, extra: unknown) => Promise<ToolReturn>): Promise<ToolReturn | InputRequiredResult>;
|
|
37
|
+
/** Release and map the refusal under the identity that actually made the request. */
|
|
38
|
+
export declare function toolError(ctx: ToolContext, err: unknown): ToolReturn;
|
|
37
39
|
/** The typed answer when the MCP request was cancelled before the upstream call settled. */
|
|
38
40
|
export declare function abortedAnswer(corr: string): ToolReturn;
|
|
39
41
|
/**
|
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';
|
|
@@ -75,12 +75,14 @@ async function frame(ctx, input, rawArgs, extra, work) {
|
|
|
75
75
|
return await work(parsed.data, mcpSignal(extra), extra);
|
|
76
76
|
}
|
|
77
77
|
catch (err) {
|
|
78
|
-
|
|
79
|
-
// V23/FT-5: the request's own credential values ride into the error wrap so a vendor body
|
|
80
|
-
// that echoes them is value-scrubbed before it crosses.
|
|
81
|
-
return errorContent(err, ctx.correlationId, requestSecrets(ctx));
|
|
78
|
+
return toolError(ctx, err);
|
|
82
79
|
}
|
|
83
80
|
}
|
|
81
|
+
/** Release and map the refusal under the identity that actually made the request. */
|
|
82
|
+
export function toolError(ctx, err) {
|
|
83
|
+
releaseClientOnError(ctx, err);
|
|
84
|
+
return errorContent(err, ctx.correlationId, requestSecrets(ctx), isDirectIdentity(ctx));
|
|
85
|
+
}
|
|
84
86
|
/**
|
|
85
87
|
* Stamp the serving unit's correlation id on a finished result (and its mirrored text block).
|
|
86
88
|
* An `input_required` result is not a tool result: it carries no envelope and is returned untouched.
|
|
@@ -165,6 +167,9 @@ const OWN_STAMP_OPS = new Set(['contracts.profitability', 'operations.revenueRol
|
|
|
165
167
|
* `autotask_read` only). The name is NOT `queryable`: the SDK row already carries `queryable: string[]`.
|
|
166
168
|
*/
|
|
167
169
|
function annotateCatalogRows(result) {
|
|
170
|
+
// The SDK's call-owned refusal evidence was already evaluated before projection.
|
|
171
|
+
if (result !== null && typeof result === 'object')
|
|
172
|
+
delete result.authFailure;
|
|
168
173
|
// 0.39.0 (#282): the truncation note is SDK-built (an enum reason, byte counts, resource keys), never vendor
|
|
169
174
|
// text; `reason` and `note` share names with vendor free-text fields, so they are recorded server-built.
|
|
170
175
|
const truncation = result?.truncation;
|
|
@@ -182,9 +187,11 @@ function annotateCatalogRows(result) {
|
|
|
182
187
|
const operation = typeof resource === 'string' ? `${resource}.query` : undefined;
|
|
183
188
|
const catalogRow = row;
|
|
184
189
|
catalogRow.queryOperation = operation !== undefined && toolForOp(operation) === 'autotask_query' ? operation : null;
|
|
185
|
-
if (
|
|
186
|
-
//
|
|
187
|
-
|
|
190
|
+
if (catalogRow.error != null) {
|
|
191
|
+
// A folded row error carries vendor text and a code without trusted HTTP status.
|
|
192
|
+
const error = { code: 'UPSTREAM_ERROR', message: 'Autotask could not provide metadata for this resource.' };
|
|
193
|
+
markServerField(error, 'message', 'server');
|
|
194
|
+
catalogRow.error = error;
|
|
188
195
|
}
|
|
189
196
|
}
|
|
190
197
|
}
|
|
@@ -288,6 +295,15 @@ export async function readOneItem(ctx, operation, args, signal, opts, projectRaw
|
|
|
288
295
|
});
|
|
289
296
|
if (result === undefined)
|
|
290
297
|
return { aborted: true, result: undefined };
|
|
298
|
+
if (operation === 'operations.fieldCatalog') {
|
|
299
|
+
// SDK rows carry the normalized, validated targets, independent of which metadata refusal won.
|
|
300
|
+
const { authFailure, rows } = result ?? {};
|
|
301
|
+
if (authFailure !== undefined && (authFailure.httpStatus === 401 || (authFailure.httpStatus === 403 && !isDirectIdentity(ctx))) &&
|
|
302
|
+
rows?.some(({ resource }) => staffReadParentFilter(resource) !== undefined) &&
|
|
303
|
+
isRegisteredMetadataRead(authFailure.operation) && rows.some(({ resource }) => authFailure.operation.startsWith(`${resource}.`))) {
|
|
304
|
+
throw errorFromStatus(authFailure.httpStatus, undefined, undefined, authFailure.operation);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
291
307
|
// Raw evidence must precede deepMarkUntrusted, which replaces excessively nested values.
|
|
292
308
|
if (projectRaw !== undefined)
|
|
293
309
|
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,16 @@ 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
|
+
: args.resource === 'document_categories'
|
|
67
|
+
? 'pass a filter on id for a known category or on parentCategoryID for categories under a known parent'
|
|
68
|
+
: isDeletedActivityAuditResource(args.resource)
|
|
69
|
+
? 'pass an audit filter such as {field: "id", op: "exist"} for bounded reads or counts'
|
|
70
|
+
: args.resource === 'internal_locations' || args.resource === 'shipping_types'
|
|
71
|
+
? 'call again with {field: "id", op: "eq", value: "<id>"} for a known record, or {field: "id", op: "exist"} for the whole entity'
|
|
72
|
+
: '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
73
|
throw new InputInvalidError(`query: filter is missing or empty; ${hint}`, 'filter');
|
|
69
74
|
}
|
|
70
75
|
// #228: totals mode (group_by / sum / count) is the SDK's operations.aggregate over the same filter
|