iit-mcp-autotask 0.63.17 → 0.64.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/.env.example +3 -0
- package/README.md +6 -8
- package/capabilities.json +5 -5
- package/dist/config/schema.d.ts +8 -0
- package/dist/config/schema.js +1 -0
- package/dist/doctor.d.ts +1 -0
- package/dist/doctor.js +1 -0
- package/dist/tools/capabilities-manifest.js +1 -0
- package/dist/tools/catalog-data.d.ts +1 -1
- package/dist/tools/catalog-data.js +3 -3
- package/dist/tools/context/client.js +3 -2
- package/dist/tools/dispatch.js +3 -3
- package/dist/tools/lists.js +3 -1
- package/dist/tools/meta.js +11 -7
- package/dist/tools/results/errors.d.ts +3 -2
- package/dist/tools/results/errors.js +20 -9
- package/dist/tools/schemas.js +2 -2
- package/dist/tools/server.js +1 -1
- package/dist/tools/write/apply.d.ts +3 -4
- package/dist/tools/write/apply.js +73 -20
- package/dist/tools/write/outcome.js +13 -4
- package/dist/tools/write/payload.d.ts +1 -1
- package/dist/tools/write/payload.js +5 -2
- package/dist/tools/write/preview.js +2 -2
- package/dist/tools/write/snapshot.js +3 -1
- package/dist/write/store/files.d.ts +5 -6
- package/dist/write/store/files.js +46 -12
- package/dist/write/store/ledger.js +1 -1
- package/package.json +2 -2
- package/server.json +2 -2
package/.env.example
CHANGED
|
@@ -88,6 +88,9 @@ AUTOTASK_PROFILE=readonly
|
|
|
88
88
|
# the vendor.
|
|
89
89
|
AUTOTASK_CACHE=on
|
|
90
90
|
|
|
91
|
+
# Opt in to masking SDK personal and business-sensitive fields in tool results.
|
|
92
|
+
# AUTOTASK_REDACT_PERSONAL_DATA=true
|
|
93
|
+
|
|
91
94
|
# --- Vendor budget (the server boots the SDK in the conservative `agent` profile; overrides here) ---
|
|
92
95
|
# These are per-client allowances. The SDK also caps each object/tracking identifier at
|
|
93
96
|
# 3 active requests and shares a conservative origin-wide 10,000-attempt hourly ceiling
|
package/README.md
CHANGED
|
@@ -544,6 +544,7 @@ non-zero on an invalid config (fail-fast) instead of failing at the first tool c
|
|
|
544
544
|
| `AUTOTASK_ALLOWED_BASE_HOSTS` | http: unless `AUTOTASK_ALLOW_ANY_BASE_HOST=true` | — | comma-separated exact hostnames or `*.suffix` subdomain suffixes a caller may name in `X-Autotask-Base-Url` (no scheme/port/path). Unset + default origin set → only that origin accepted. Unset + no default → boot refused unless the lab-only flag. **Recommended production value: `*.autotask.net`**. Literal private-IP origins are always refused. |
|
|
545
545
|
| `AUTOTASK_ALLOW_ANY_BASE_HOST` | no | `false` | lab-only opt-in to boot with neither allow-list nor default origin; `warn`-logged at boot (decision D-4); refused with the operator profile. Not set in production. |
|
|
546
546
|
| `AUTOTASK_CACHE` | no | `on` | the single off switch for the SDK's per-tenant in-process caches (see [Per-tenant pool & cache](#per-tenant-pool--cache)): `on` (default) sends no cache block — the SDK's default-on caches apply to each pooled tenant client (read ~5 min + the reference tables at 1 h, field metadata ~5 min, plus the fuzzy company-name index below); `off` sends `cache: false` (every read re-dials the vendor) |
|
|
547
|
+
| `AUTOTASK_REDACT_PERSONAL_DATA` | no | `false` | Set to `true` to mask the SDK's personal and business-sensitive fields in tool results and dry-run payloads. |
|
|
547
548
|
| `AUTOTASK_OUTPUT_DIR` | no | unset | the ONE directory the `output_path` option may write into (the bounded query tools and the invoice export; stdio transport only). Unset = defaults to `output/` under `AUTOTASK_STATE_DIR` (the feature refuses when neither is set); must be absolute, must already EXIST (the server never creates the root) and must not be the filesystem root. A caller path is relative to this root, and the root and target are canonically resolved (`realpath`) so a traversal or symlink escape is refused — with nothing created outside the root. See [Query results](#query-results-tsv-output_path-and-the-saved-file-shape) |
|
|
548
549
|
| `AUTOTASK_QUERY_MAX_BYTES` | no | 262144 (256 KiB) | the `autotask_query` rows-mode response budget in bytes (16384 to 4194304): a larger answer is cut to the longest whole-row prefix that fits, with `hasMore` and `bytesCapped` (see [Query results](#query-results-tsv-output_path-and-the-saved-file-shape)); totals, `output_path` and `autotask_read` are not capped |
|
|
549
550
|
| `AUTOTASK_RATE_LIMIT_PER_HOUR` | no | 8000 (agent profile) | override the SDK's local hourly allowance (at most 10,000; `null`/off is rejected at boot); the shared SDK origin ceiling remains enforced |
|
|
@@ -759,18 +760,15 @@ guards (rate limiter, 429 cooldown) — a worse security posture, not a safer on
|
|
|
759
760
|
|
|
760
761
|
## Security posture
|
|
761
762
|
|
|
762
|
-
- **
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
`test/integration/redaction-secret-reads.test.ts`). The confidential class this covers: the
|
|
763
|
+
- **Personal-data redaction is opt-in.** Set `AUTOTASK_REDACT_PERSONAL_DATA=true` to retain the
|
|
764
|
+
masking behavior of earlier releases. `doctor` and the `server` part of `autotask_tenant_status`
|
|
765
|
+
report the effective setting. Opt-in masking covers contacts' personal data and the
|
|
766
766
|
`configuration_items` domain fields (`domain`, `domainExpirationDateTime`,
|
|
767
767
|
`domainLastUpdatedDateTime`, `domainRegistrationDateTime`), the RMM device-audit fields
|
|
768
768
|
(`rmmDeviceAuditExternalIPAddress`, `rmmDeviceAuditIPAddress`, `rmmDeviceAuditMacAddress`,
|
|
769
769
|
`rmmDeviceAuditMobileNumber`, `rmmDeviceAuditSNMPContact`), `primaryContact`, `taxID` and
|
|
770
|
-
`webAddress`
|
|
771
|
-
|
|
772
|
-
fields are not — so a filter on a redacted field still matches server-side, but the answer cannot
|
|
773
|
-
show the triggering value.
|
|
770
|
+
`webAddress` fields. The SDK always masks the exact field names `password`, `secretKey` and `secret`. Autotask still
|
|
771
|
+
evaluates filters against stored values when result masking is enabled.
|
|
774
772
|
- **Untrusted-content wrapping:** vendor free text in results stays wrapped in this server's own
|
|
775
773
|
`<untrusted_content>` markers end-to-end (the pinned SDK returns read-path values raw — its
|
|
776
774
|
wrapper is a projection-layer helper; the server wraps once at the choke point: exactly once,
|
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,413 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",
|
|
@@ -106,7 +106,7 @@
|
|
|
106
106
|
},
|
|
107
107
|
{
|
|
108
108
|
"id": "autotask.generic.read",
|
|
109
|
-
"description": "Run one or several reads in one call by exact registry key: unbilled work, profitability and margin, SLA health. Scope by company/contract ids (unscoped = tenant walk); totals: autotask_query group_by; slim: includeFields, noteChars.",
|
|
109
|
+
"description": "Run one or several reads in one call by exact registry key: unbilled work, profitability and margin, SLA health. Scope by company/contract ids where supported (unscoped = tenant walk); totals: autotask_query group_by; slim: includeFields, noteChars.",
|
|
110
110
|
"mcpPrimitive": "tool",
|
|
111
111
|
"toolName": "autotask_read",
|
|
112
112
|
"type": "read",
|
|
@@ -138,13 +138,13 @@
|
|
|
138
138
|
},
|
|
139
139
|
{
|
|
140
140
|
"id": "autotask.discovery.query",
|
|
141
|
-
"description": "List records
|
|
141
|
+
"description": "List records with a filter (e.g. tickets, time entries, service calls, contracts, time off). Totals, no rows: group_by, sum, count (hours logged by ticket, how many match). By id: id in. Scope by company ids if supported (unscoped = tenant walk).",
|
|
142
142
|
"mcpPrimitive": "tool",
|
|
143
143
|
"toolName": "autotask_query",
|
|
144
144
|
"type": "read",
|
|
145
145
|
"toolset": "core",
|
|
146
146
|
"profile": "readonly",
|
|
147
|
-
"backingOperation": "
|
|
147
|
+
"backingOperation": "node-autotask/operations invokeRead (any effect=read <resource>.query key) | operations.aggregate",
|
|
148
148
|
"annotations": {
|
|
149
149
|
"readOnly": true,
|
|
150
150
|
"idempotent": true,
|
|
@@ -480,7 +480,7 @@
|
|
|
480
480
|
"autotask_describe",
|
|
481
481
|
"autotask_read"
|
|
482
482
|
],
|
|
483
|
-
"backingRegistryOperations":
|
|
483
|
+
"backingRegistryOperations": 1413,
|
|
484
484
|
"note": "autotask_catalog finds the exact operation key (ranked search), autotask_describe serves its contract, autotask_read runs any effect=read key. Writes go through the operator profile (autotask_write then autotask_apply); authenticate.* is never served."
|
|
485
485
|
},
|
|
486
486
|
"schemas": {}
|
package/dist/config/schema.d.ts
CHANGED
|
@@ -99,6 +99,10 @@ export declare const CONFIG_FIELDS: z.ZodObject<{
|
|
|
99
99
|
on: "on";
|
|
100
100
|
off: "off";
|
|
101
101
|
}>>;
|
|
102
|
+
AUTOTASK_REDACT_PERSONAL_DATA: z.ZodPipe<z.ZodDefault<z.ZodEnum<{
|
|
103
|
+
true: "true";
|
|
104
|
+
false: "false";
|
|
105
|
+
}>>, z.ZodTransform<boolean, "true" | "false">>;
|
|
102
106
|
AUTOTASK_OUTPUT_DIR: z.ZodOptional<z.ZodPreprocess<z.ZodString, unknown>>;
|
|
103
107
|
AUTOTASK_QUERY_MAX_BYTES: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
|
|
104
108
|
AUTOTASK_RATE_LIMIT_PER_HOUR: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
|
|
@@ -158,6 +162,10 @@ export declare const schema: z.ZodObject<{
|
|
|
158
162
|
on: "on";
|
|
159
163
|
off: "off";
|
|
160
164
|
}>>;
|
|
165
|
+
AUTOTASK_REDACT_PERSONAL_DATA: z.ZodPipe<z.ZodDefault<z.ZodEnum<{
|
|
166
|
+
true: "true";
|
|
167
|
+
false: "false";
|
|
168
|
+
}>>, z.ZodTransform<boolean, "true" | "false">>;
|
|
161
169
|
AUTOTASK_OUTPUT_DIR: z.ZodOptional<z.ZodPreprocess<z.ZodString, unknown>>;
|
|
162
170
|
AUTOTASK_QUERY_MAX_BYTES: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
|
|
163
171
|
AUTOTASK_RATE_LIMIT_PER_HOUR: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
|
package/dist/config/schema.js
CHANGED
|
@@ -188,6 +188,7 @@ export const CONFIG_FIELDS = z
|
|
|
188
188
|
* sent — every SDK cache channel is off and every read re-dials the vendor.
|
|
189
189
|
*/
|
|
190
190
|
AUTOTASK_CACHE: z.enum(['on', 'off']).default('on'),
|
|
191
|
+
AUTOTASK_REDACT_PERSONAL_DATA: z.enum(['true', 'false']).default('false').transform((v) => v === 'true'),
|
|
191
192
|
/**
|
|
192
193
|
* The `output_path` root (issue #11, ruling N6): the ONE directory the bounded query tools'
|
|
193
194
|
* `output_path` option may write into. Optional at boot — the feature refuses per call when it
|
package/dist/doctor.d.ts
CHANGED
|
@@ -58,6 +58,7 @@ export interface DoctorReport {
|
|
|
58
58
|
readonly ok: boolean;
|
|
59
59
|
readonly transport: Config['MCP_TRANSPORT'];
|
|
60
60
|
readonly dialed: number;
|
|
61
|
+
readonly redactPersonalData: boolean;
|
|
61
62
|
readonly credentials: readonly DoctorCredentialCheck[];
|
|
62
63
|
readonly bases: readonly DoctorBaseCheck[];
|
|
63
64
|
readonly hostPolicy: DoctorHostPolicy;
|
package/dist/doctor.js
CHANGED
|
@@ -30,6 +30,7 @@ const BACKING = {
|
|
|
30
30
|
autotask_catalog: 'node-autotask/capabilities registry + MCP_TOOL_CATALOG.json',
|
|
31
31
|
autotask_describe: 'registry records + operations.relationshipMap',
|
|
32
32
|
autotask_read: 'node-autotask/operations invokeRead (any effect=read key)',
|
|
33
|
+
autotask_query: 'node-autotask/operations invokeRead (any effect=read <resource>.query key) | operations.aggregate',
|
|
33
34
|
autotask_write: 'node-autotask/operations invokeWrite / invokeDelete dry run (the keys AUTOTASK_WRITE lists)',
|
|
34
35
|
autotask_apply: 'node-autotask/operations invokeWrite / invokeDelete (exactly the previewed plan, no hard rule)',
|
|
35
36
|
autotask_apply_destructive: 'node-autotask/operations invokeWrite / invokeDelete (exactly the previewed plan that hits a hard rule)',
|
|
@@ -108,7 +108,7 @@ export declare function sdkCacheOptions(cache: 'on' | 'off'): Pick<AutotaskConfi
|
|
|
108
108
|
* fails the boot (or the CI test) instead of quietly shipping a tool surface that no longer
|
|
109
109
|
* describes the SDK behind it.
|
|
110
110
|
*/
|
|
111
|
-
export declare const BUILT_AGAINST_PLAN_HASH = "
|
|
111
|
+
export declare const BUILT_AGAINST_PLAN_HASH = "fe0c9ce6a957bb730c1bdb9fb46498e61e2d04cc1cdd861d796ac26f982ab505";
|
|
112
112
|
/**
|
|
113
113
|
* Fail fast when the installed SDK's plan has moved out from under this surface.
|
|
114
114
|
* Called at boot (main.ts) and safe to call repeatedly (pure comparison).
|
|
@@ -133,9 +133,9 @@ export const TOOL_DESCRIPTIONS = {
|
|
|
133
133
|
autotask_guide: 'Step-by-step playbooks for multi-step Autotask tasks. No args: the index; {skill} returns one playbook, {skill, section} one section. Static text, no vendor call. Use it first when a task needs several tools.',
|
|
134
134
|
autotask_catalog: `Find the exact operation key for anything without a dedicated tool: ranked search (q) over the ${RECORDS.length.toLocaleString('en-US')} registry operations, with effect and whether this deployment serves it. No vendor call.`,
|
|
135
135
|
autotask_describe: 'One operation\'s (registry key or tool name) exact input/output contract, examples, errors, policy verdict and playbooks (operation), or one resource\'s relationship map: parent, children, lookup keys (resource). No vendor call.',
|
|
136
|
-
autotask_read: 'Run one or several reads in one call by exact registry key: unbilled work, profitability and margin, SLA health. Scope by company/contract ids (unscoped = tenant walk); totals: autotask_query group_by; slim: includeFields, noteChars.',
|
|
136
|
+
autotask_read: 'Run one or several reads in one call by exact registry key: unbilled work, profitability and margin, SLA health. Scope by company/contract ids where supported (unscoped = tenant walk); totals: autotask_query group_by; slim: includeFields, noteChars.',
|
|
137
137
|
autotask_resolve: 'Find the record for an identifier: id or name, ticket number, CI serial, contact email (by), staff by email, user name or name (resource resources, include_api_users); one resource or a sweep. Exact, then contains; companies add fuzzy candidates.',
|
|
138
|
-
autotask_query: 'List records
|
|
138
|
+
autotask_query: 'List records with a filter (e.g. tickets, time entries, service calls, contracts, time off). Totals, no rows: group_by, sum, count (hours logged by ticket, how many match). By id: id in. Scope by company ids if supported (unscoped = tenant walk).',
|
|
139
139
|
autotask_tenant_status: 'Identity (API user + impersonated user), Autotask API version, this server\'s package/SDK version and profile (server), request thresholds, and the time zone of the people asking, with local and UTC time (time). Use it first to check credentials.',
|
|
140
140
|
autotask_ticket_full_context: 'One ticket with its company, contact, assigned resource, project, notes, time entries and attachment metadata. Missing parts degrade to typed absent; a missing ticket is not found.',
|
|
141
141
|
autotask_company_full_profile: 'One company with locations, contacts, notes, open tickets and projects (capped: true = more exist; raise the limit). fields {part:[names]} trims columns. Open = not tenant-closed. Missing parts degrade to typed absent.',
|
|
@@ -190,7 +190,7 @@ export function sdkCacheOptions(cache) {
|
|
|
190
190
|
* fails the boot (or the CI test) instead of quietly shipping a tool surface that no longer
|
|
191
191
|
* describes the SDK behind it.
|
|
192
192
|
*/
|
|
193
|
-
export const BUILT_AGAINST_PLAN_HASH = '
|
|
193
|
+
export const BUILT_AGAINST_PLAN_HASH = 'fe0c9ce6a957bb730c1bdb9fb46498e61e2d04cc1cdd861d796ac26f982ab505';
|
|
194
194
|
/**
|
|
195
195
|
* Fail fast when the installed SDK's plan has moved out from under this surface.
|
|
196
196
|
* Called at boot (main.ts) and safe to call repeatedly (pure comparison).
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** SDK client construction (base options, placeholder, stdio client) and the default SDK ops bundle (issue #91). */
|
|
2
|
-
import {
|
|
2
|
+
import { statusBasedVendorCode } from '../results/errors.js';
|
|
3
3
|
import { AutotaskClient } 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';
|
|
@@ -30,6 +30,7 @@ export function buildSdkBaseOptions(config, log) {
|
|
|
30
30
|
profile: 'agent',
|
|
31
31
|
// Keep LLM-facing name/label siblings enabled (SDK labels are opt-in).
|
|
32
32
|
labels: true,
|
|
33
|
+
redactPersonalData: config.AUTOTASK_REDACT_PERSONAL_DATA,
|
|
33
34
|
// Tool calls must never hang inside a vendor maintenance window (issue #252): the wait is
|
|
34
35
|
// 0, so the SDK's shared per-zone maintenance gate opens and surfaces the typed
|
|
35
36
|
// MaintenanceError at once (node-autotask 0.40.0 #285) instead of a call riding out the
|
|
@@ -59,7 +60,7 @@ export function buildSdkBaseOptions(config, log) {
|
|
|
59
60
|
const operation = typeof e.operation === 'string' ? e.operation : undefined;
|
|
60
61
|
const status = typeof e.status === 'number' ? e.status : undefined;
|
|
61
62
|
const errorCode = typeof e.errorCode === 'string' && e.errorCode !== 'MAINTENANCE'
|
|
62
|
-
?
|
|
63
|
+
? statusBasedVendorCode(operation, status) ?? e.errorCode
|
|
63
64
|
: e.errorCode === 'MAINTENANCE' ? 'MAINTENANCE' : undefined;
|
|
64
65
|
log.info('autotask request', {
|
|
65
66
|
...(typeof e.correlationId === 'string' ? { correlationId: e.correlationId } : {}),
|
package/dist/tools/dispatch.js
CHANGED
|
@@ -17,7 +17,7 @@ import { assertFilterShape, QUERY_LIMIT, QUERY_MAX_ROWS } from './schemas.js';
|
|
|
17
17
|
import { RECORDS, toolForOp } from './catalog-data.js';
|
|
18
18
|
import { AUTOTASK_BASE_PATH } from '../base-hosts.js';
|
|
19
19
|
import { releaseClientOnError } from './context/derive.js';
|
|
20
|
-
import { abortedResult, closedArgsError, errorContent,
|
|
20
|
+
import { abortedResult, closedArgsError, errorContent, isShapeOnlyVendorOperation, refusalContent } from './results/errors.js';
|
|
21
21
|
import { crossResourceUntrusted, isFileOperation, markFilePayload, markResult, markServerField } from './results/untrusted.js';
|
|
22
22
|
import { mirrorEnvelope } from './results/envelope.js';
|
|
23
23
|
import { assertOperationPermitted } from '../policy.js';
|
|
@@ -182,9 +182,9 @@ function annotateCatalogRows(result) {
|
|
|
182
182
|
const operation = typeof resource === 'string' ? `${resource}.query` : undefined;
|
|
183
183
|
const catalogRow = row;
|
|
184
184
|
catalogRow.queryOperation = operation !== undefined && toolForOp(operation) === 'autotask_query' ? operation : null;
|
|
185
|
-
if (
|
|
185
|
+
if (isShapeOnlyVendorOperation(operation) && catalogRow.error != null) {
|
|
186
186
|
// The SDK's row error carries vendor text and a code without trusted HTTP status.
|
|
187
|
-
catalogRow.error = { code: 'UPSTREAM_ERROR', message: 'Autotask could not provide
|
|
187
|
+
catalogRow.error = { code: 'UPSTREAM_ERROR', message: 'Autotask could not provide metadata for this resource.' };
|
|
188
188
|
}
|
|
189
189
|
}
|
|
190
190
|
}
|
package/dist/tools/lists.js
CHANGED
|
@@ -62,7 +62,9 @@ export function buildQuery(ctx) {
|
|
|
62
62
|
// one sentence that names the scope to add (data.message and reasons[].detail both carry it whole)
|
|
63
63
|
const hint = isDeletedActivityAuditResource(args.resource)
|
|
64
64
|
? 'pass an audit filter such as {field: "id", op: "exist"} for bounded reads or counts'
|
|
65
|
-
:
|
|
65
|
+
: args.resource === 'internal_locations' || args.resource === 'shipping_types'
|
|
66
|
+
? 'call again with {field: "id", op: "eq", value: "<id>"} for a known record, or {field: "id", op: "exist"} for the whole entity'
|
|
67
|
+
: 'call again with a scope such as {field: "companyID", op: "eq", value: "<id>"} (time_entries: ticket.companyID), or {field: "id", op: "exist"} for the whole entity';
|
|
66
68
|
throw new InputInvalidError(`query: filter is missing or empty; ${hint}`, 'filter');
|
|
67
69
|
}
|
|
68
70
|
// #228: totals mode (group_by / sum / count) is the SDK's operations.aggregate over the same filter
|
package/dist/tools/meta.js
CHANGED
|
@@ -26,7 +26,7 @@ import { 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';
|
|
29
|
-
import {
|
|
29
|
+
import { isShapeOnlyVendorOperation, typedErrorPayload } from './results/errors.js';
|
|
30
30
|
import { markResult, sanitiseVendorOutput, UNTRUSTED_TEXT_CAP } from './results/untrusted.js';
|
|
31
31
|
import { errorEnvelope, ok, TRUNCATION_MARKER } from './results/envelope.js';
|
|
32
32
|
import { compileBm25 } from './rank.js';
|
|
@@ -247,10 +247,14 @@ export function buildDescribe(ctx) {
|
|
|
247
247
|
reachable: (r?.reachable ?? true) && refusalReason(k, ctx.record(k), ctx.config, ctx.writable, ctx.write?.runScope) === null,
|
|
248
248
|
};
|
|
249
249
|
});
|
|
250
|
-
|
|
250
|
+
const queryTool = operation === 'autotask_query';
|
|
251
|
+
return ok(queryTool
|
|
252
|
+
? 'Example registry keys for autotask_query. Find more query resources via autotask_catalog, then describe the exact key.'
|
|
253
|
+
: `"${operation}" serves ${keys.length} registry keys; pass one as operation for its full record.`, {
|
|
251
254
|
tool: operation,
|
|
252
255
|
...toolServed(ctx, operation),
|
|
253
256
|
operations: rows,
|
|
257
|
+
...(queryTool ? { operationsScope: 'examples' } : {}),
|
|
254
258
|
paramNames: paramNames(keys[0], ctx.record(keys[0])),
|
|
255
259
|
});
|
|
256
260
|
}
|
|
@@ -524,8 +528,8 @@ function staffAttachmentArgs(rec) {
|
|
|
524
528
|
? 'parentId and id each require a positive safe integer JSON number.'
|
|
525
529
|
: 'parentId requires a positive safe integer JSON number. data is the attachment payload.';
|
|
526
530
|
}
|
|
527
|
-
function
|
|
528
|
-
if (!
|
|
531
|
+
function operatorWriteArgs(rec) {
|
|
532
|
+
if (!isShapeOnlyVendorOperation(rec.id) || !isWriteEffect(rec))
|
|
529
533
|
return undefined;
|
|
530
534
|
const ids = ['parentId', 'id'].filter(key => rec.inputSchema[key] !== undefined);
|
|
531
535
|
if (ids.length === 0)
|
|
@@ -549,7 +553,7 @@ function servedRecord(rec) {
|
|
|
549
553
|
if (usage !== undefined && usage !== md?.usage)
|
|
550
554
|
projected.metadata = { ...md, usage };
|
|
551
555
|
const staffArgs = staffAttachmentArgs(rec);
|
|
552
|
-
const args = staffArgs ??
|
|
556
|
+
const args = staffArgs ?? operatorWriteArgs(rec);
|
|
553
557
|
if (args !== undefined) {
|
|
554
558
|
const schema = { ...rec.inputSchema };
|
|
555
559
|
for (const key of ['parentId', 'id']) {
|
|
@@ -620,7 +624,7 @@ function summariseRecord(ctx, operation, viaTool) {
|
|
|
620
624
|
...(tool !== undefined ? { tool, ...toolServed(ctx, tool) } : {}),
|
|
621
625
|
purpose: capText(text(md.purpose) || text(row?.purpose), SUMMARY_CAPS.purpose, 'purpose', cut),
|
|
622
626
|
requiredArgs: row?.requiredArgs ?? [],
|
|
623
|
-
args: capText(staffAttachmentArgs(rec) ??
|
|
627
|
+
args: capText(staffAttachmentArgs(rec) ?? operatorWriteArgs(rec) ?? text(md.args), SUMMARY_CAPS.args, 'args', cut),
|
|
624
628
|
usage: capText(text(compactUsage(rec, true)), SUMMARY_CAPS.usage, 'usage', cut),
|
|
625
629
|
reachable: reason === null,
|
|
626
630
|
why_not: reason,
|
|
@@ -787,7 +791,7 @@ export function buildTenantStatus(ctx) {
|
|
|
787
791
|
// late failure cannot outlive this request, and assemble only in requested order.
|
|
788
792
|
const settled = await Promise.allSettled(parts.map(async (part) => {
|
|
789
793
|
if (part === 'server') {
|
|
790
|
-
return { value: { name: SERVER_NAME, version: SERVER_VERSION, sdkVersion: SDK_VERSION, profile: ctx.config.AUTOTASK_PROFILE, ticketNoteVerificationProjection: TICKET_NOTE_VERIFICATION_PROJECTION, readRuntime: readRuntimeProof(ctx.client) } };
|
|
794
|
+
return { value: { name: SERVER_NAME, version: SERVER_VERSION, sdkVersion: SDK_VERSION, profile: ctx.config.AUTOTASK_PROFILE, redactPersonalData: ctx.config.AUTOTASK_REDACT_PERSONAL_DATA, ticketNoteVerificationProjection: TICKET_NOTE_VERIFICATION_PROJECTION, readRuntime: readRuntimeProof(ctx.client) } };
|
|
791
795
|
}
|
|
792
796
|
if (part === 'time')
|
|
793
797
|
return { value: zoneClock(ctx.config.AUTOTASK_USER_TIMEZONE) };
|
|
@@ -128,10 +128,11 @@ export declare function vendorShapeDiagnostic(err: unknown, secrets: readonly st
|
|
|
128
128
|
*/
|
|
129
129
|
export declare function isAuthFailure(err: unknown): boolean;
|
|
130
130
|
export declare function isKnowledgeBaseRootOperation(operation: string | undefined): boolean;
|
|
131
|
+
export declare function isShapeOnlyVendorOperation(operation: string | undefined): boolean;
|
|
131
132
|
/** A vendor failure's canonical status code, also used in transport audit logs. */
|
|
132
|
-
export declare function
|
|
133
|
+
export declare function statusBasedVendorCode(operation: string | undefined, status: number | undefined): string | undefined;
|
|
133
134
|
/** Strip vendor-supplied codes while preserving trusted SDK envelope and maintenance classifications. */
|
|
134
|
-
export declare function
|
|
135
|
+
export declare function shapeOnlyVendorCode(operation: string | undefined, httpStatus: number | undefined, error: unknown): string | undefined;
|
|
135
136
|
/**
|
|
136
137
|
* Surface the SDK's error contract so the model can correct itself (architecture section 8:
|
|
137
138
|
* wrap, never flatten). The SDK's fields cross this boundary: `code`, `category`, `retryable`,
|
|
@@ -305,19 +305,23 @@ export function isAuthFailure(err) {
|
|
|
305
305
|
export function isKnowledgeBaseRootOperation(operation) {
|
|
306
306
|
return operation !== undefined && /^knowledge_base_(articles|categories)\./.test(operation);
|
|
307
307
|
}
|
|
308
|
+
export function isShapeOnlyVendorOperation(operation) {
|
|
309
|
+
return isKnowledgeBaseRootOperation(operation)
|
|
310
|
+
|| (operation !== undefined && /^(inventory_locations|internal_locations|shipping_types)\./.test(operation));
|
|
311
|
+
}
|
|
308
312
|
/** A vendor failure's canonical status code, also used in transport audit logs. */
|
|
309
|
-
export function
|
|
310
|
-
return
|
|
313
|
+
export function statusBasedVendorCode(operation, status) {
|
|
314
|
+
return isShapeOnlyVendorOperation(operation) && status !== undefined && status >= 300
|
|
311
315
|
? errorFromStatus(status, undefined).code : undefined;
|
|
312
316
|
}
|
|
313
317
|
/** Strip vendor-supplied codes while preserving trusted SDK envelope and maintenance classifications. */
|
|
314
|
-
export function
|
|
318
|
+
export function shapeOnlyVendorCode(operation, httpStatus, error) {
|
|
315
319
|
const vendorError = error?.vendorError;
|
|
316
|
-
if (!
|
|
320
|
+
if (!isShapeOnlyVendorOperation(operation) || (httpStatus === undefined && vendorError === undefined))
|
|
317
321
|
return undefined;
|
|
318
322
|
if (error instanceof MaintenanceError)
|
|
319
323
|
return 'MAINTENANCE';
|
|
320
|
-
return
|
|
324
|
+
return statusBasedVendorCode(operation, httpStatus)
|
|
321
325
|
?? (vendorError === undefined && isAutotaskError(error) ? error.code : 'AUTOTASK_ERROR');
|
|
322
326
|
}
|
|
323
327
|
/**
|
|
@@ -348,7 +352,7 @@ export function typedErrorPayload(err, correlationId, secrets = []) {
|
|
|
348
352
|
const bool = (v) => (typeof v === 'boolean' ? v : undefined);
|
|
349
353
|
const httpStatus = num(e.httpStatus);
|
|
350
354
|
const operation = str(e.operation);
|
|
351
|
-
const vendorCode =
|
|
355
|
+
const vendorCode = shapeOnlyVendorCode(operation, httpStatus, err);
|
|
352
356
|
const shapeOnlyVendorError = vendorCode !== undefined;
|
|
353
357
|
const authFailure = shapeOnlyVendorError
|
|
354
358
|
? vendorCode === 'UNAUTHORIZED' || vendorCode === 'FORBIDDEN'
|
|
@@ -375,16 +379,23 @@ export function typedErrorPayload(err, correlationId, secrets = []) {
|
|
|
375
379
|
// upstream body into err.message by design, and a SHORT body (a credential echo) would
|
|
376
380
|
// otherwise cross under the 200-char bound. Other client-side errors (no httpStatus) keep the
|
|
377
381
|
// SDK's own deterministic text (bounded as before).
|
|
378
|
-
|
|
382
|
+
const knowledgeBase = isKnowledgeBaseRootOperation(operation);
|
|
383
|
+
const inventoryLocation = operation?.startsWith('inventory_locations.') === true;
|
|
384
|
+
if (shapeOnlyVendorError && code === 'NOT_FOUND' && (knowledgeBase || operation?.endsWith('.get') === true)) {
|
|
379
385
|
payload.message = operation === 'knowledge_base_articles.get'
|
|
380
386
|
? 'No published article was visible to this API user at the requested ID.'
|
|
381
|
-
:
|
|
387
|
+
: knowledgeBase
|
|
388
|
+
? 'No Knowledge Base record was visible to this API user at the requested ID.'
|
|
389
|
+
: operation === 'inventory_locations.get'
|
|
390
|
+
? 'No inventory location was visible to this API user at the requested ID.'
|
|
391
|
+
: 'No record was visible to this API user at the requested ID.';
|
|
382
392
|
}
|
|
383
393
|
else if (httpStatus !== undefined) {
|
|
384
394
|
payload.message = shapeMessage(httpStatus, url);
|
|
385
395
|
}
|
|
386
396
|
else if (shapeOnlyVendorError) {
|
|
387
|
-
payload.message = 'Autotask refused the Knowledge Base operation.'
|
|
397
|
+
payload.message = knowledgeBase ? 'Autotask refused the Knowledge Base operation.'
|
|
398
|
+
: inventoryLocation ? 'Autotask refused the inventory location operation.' : 'Autotask refused the operation.';
|
|
388
399
|
}
|
|
389
400
|
else {
|
|
390
401
|
payload.message = sdkValidation
|
package/dist/tools/schemas.js
CHANGED
|
@@ -28,7 +28,7 @@ export const OP_KEY = z
|
|
|
28
28
|
.max(80)
|
|
29
29
|
.regex(/^[a-z][a-z0-9_]*\.[a-zA-Z][a-zA-Z0-9]*$/, {
|
|
30
30
|
error: (iss) => typeof iss.input === 'string' && /^autotask_[a-z_]+$/.test(iss.input)
|
|
31
|
-
? `"${iss.input}" is an MCP tool name, not a registry key — call the tool directly
|
|
31
|
+
? `"${iss.input}" is an MCP tool name, not a registry key — call the tool directly or find a registry key via autotask_catalog`
|
|
32
32
|
: 'expected an exact registry key, e.g. tickets.get',
|
|
33
33
|
});
|
|
34
34
|
/** The positional args of one registry operation (the registry's widest operation takes 3). */
|
|
@@ -188,7 +188,7 @@ const DESCRIBE_OP = z
|
|
|
188
188
|
.max(80)
|
|
189
189
|
.regex(/^(?:[a-z][a-z0-9_]*\.[a-zA-Z][a-zA-Z0-9]*|autotask_[a-z0-9_]+)$/, 'expected a registry key (e.g. tickets.get) or an MCP tool name (e.g. autotask_query)');
|
|
190
190
|
export const DESCRIBE_INPUT = z.object({
|
|
191
|
-
operation: DESCRIBE_OP.optional().describe('
|
|
191
|
+
operation: DESCRIBE_OP.optional().describe('Registry key or MCP tool name. Use autotask_catalog to find query resources.'),
|
|
192
192
|
summary: z.boolean().optional().describe('true: purpose, args and usage only.'),
|
|
193
193
|
full: z.boolean().optional().describe('true: the complete record (default slim).'),
|
|
194
194
|
resource: z.string().regex(/^[a-z][a-z0-9_]{0,59}$/).optional().describe('Resource key for its relationship map, e.g. tickets.'),
|
package/dist/tools/server.js
CHANGED
|
@@ -79,7 +79,7 @@ Routing:
|
|
|
79
79
|
|
|
80
80
|
Filters: [{field, op, value}]; op is ${FILTER_OPS.slice(0, -1).join(', ')} or ${FILTER_OPS.at(-1)}; group with {op: "and"|"or", items: [...]}. Field names are vendor-cased: operations.fieldCatalog args [{resources:[key], fields:[names], labels:true}], not getFieldInfo. A bare object is refused. in/notIn take an array or "1,2,3".
|
|
81
81
|
Dates: UTC ISO-8601; dateWorked is a YYYY-MM-DD date, never converted.
|
|
82
|
-
Scope
|
|
82
|
+
Scope queries by supported IDs. Time entries use ticket.companyID. Unscoped is a tenant-wide walk, refused above ${UNSCOPED_WALK_THRESHOLD} rows unless acknowledge_unscoped (query) or acknowledgeUnscoped (read). Totals: autotask_query group_by/sum (same scope); time: both hoursWorked and hoursToBill.
|
|
83
83
|
A list miss is not proof of absence: verify by id.${zone}`;
|
|
84
84
|
}
|
|
85
85
|
/** The full identity stamp (the `/metadata` build block — the era pair, FR-2). */
|
|
@@ -26,10 +26,9 @@ interface MissStore<E> {
|
|
|
26
26
|
append(entry: E): void;
|
|
27
27
|
}
|
|
28
28
|
/**
|
|
29
|
-
* Record
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
* answer instead of letting a replay quietly answer plain ok.
|
|
29
|
+
* Record read-back verification as a later ledger line (the latest line wins on replay).
|
|
30
|
+
* Wait briefly for a concurrent apply to release the op lock. Return false if the result
|
|
31
|
+
* could not be recorded.
|
|
33
32
|
*/
|
|
34
33
|
export declare function recordMiss<E>(store: MissStore<E>, entry: E, attempts?: number, waitMs?: number): Promise<boolean>;
|
|
35
34
|
/** Build an apply tool (`destructive`: autotask_apply_destructive); human confirmation happens outside the apply lock. */
|
|
@@ -13,7 +13,7 @@ import { classifyWriteOutcome, MaintenanceError, MoveRefusedError } from 'node-a
|
|
|
13
13
|
import { notPersistedFields } from 'node-autotask/operations';
|
|
14
14
|
import { stripUntrustedDeep } from 'node-autotask/untrusted';
|
|
15
15
|
import { InputInvalidError, requestSecrets, readOneItem } from '../dispatch.js';
|
|
16
|
-
import { abortedResult,
|
|
16
|
+
import { abortedResult, isShapeOnlyVendorOperation, shapeOnlyVendorCode, typedErrorPayload } from '../results/errors.js';
|
|
17
17
|
import {} from '../results/envelope.js';
|
|
18
18
|
import { ConfigError } from '../../config/schema.js';
|
|
19
19
|
import { canonicalJson, planHashOf } from '../../write/canonical.js';
|
|
@@ -273,7 +273,12 @@ async function send(a, s) {
|
|
|
273
273
|
...base,
|
|
274
274
|
state: 'succeeded',
|
|
275
275
|
at: now(),
|
|
276
|
-
outcome: createdId === undefined ? {} : {
|
|
276
|
+
outcome: createdId === undefined ? {} : {
|
|
277
|
+
id: createdId,
|
|
278
|
+
...(['inventory_locations.create', 'inventory_locations.update'].includes(record.id)
|
|
279
|
+
? { code: 'READBACK_UNVERIFIED' }
|
|
280
|
+
: {}),
|
|
281
|
+
},
|
|
277
282
|
...(shape.startsWith('create') && createdId !== undefined
|
|
278
283
|
? { created: { resource: record.resource, id: createdId, companyIds: plan.facts.companyIds, principal: plan.principal, tenantId: plan.tenantId } }
|
|
279
284
|
: {}),
|
|
@@ -300,13 +305,15 @@ async function send(a, s) {
|
|
|
300
305
|
const classified = classifyWriteOutcome(err);
|
|
301
306
|
let c = classified;
|
|
302
307
|
if (err instanceof MaintenanceError) {
|
|
303
|
-
//
|
|
308
|
+
// These SDK guard reads happen before the mutation is sent.
|
|
304
309
|
const articleGuardRead = record.resource === 'knowledge_base_articles'
|
|
305
310
|
&& (err.operation === 'knowledge_base_categories.get' || err.operation === 'knowledge_base_articles.get'
|
|
306
311
|
|| err.operation === 'knowledge_base_articles.getFieldInfo');
|
|
307
312
|
const categoryMergeRead = record.id === 'knowledge_base_categories.update'
|
|
308
313
|
&& err.operation === 'knowledge_base_categories.get';
|
|
309
|
-
|
|
314
|
+
const inventoryLocationGuardRead = record.id === 'inventory_locations.update'
|
|
315
|
+
&& err.operation === 'inventory_locations.get';
|
|
316
|
+
if (articleGuardRead || categoryMergeRead || inventoryLocationGuardRead) {
|
|
310
317
|
c = { ...classified, state: 'failed', retryable: true };
|
|
311
318
|
}
|
|
312
319
|
else if (err.notSent !== true && err.httpStatus !== undefined && (err.httpStatus < 200 || err.httpStatus >= 300)) {
|
|
@@ -314,9 +321,9 @@ async function send(a, s) {
|
|
|
314
321
|
}
|
|
315
322
|
}
|
|
316
323
|
// a definite refusal keeps the vendor's first message (capped, sanitised) so a replay or a later investigation can say why
|
|
317
|
-
const said = c.state === 'failed' && !c.retryable && !
|
|
324
|
+
const said = c.state === 'failed' && !c.retryable && !isShapeOnlyVendorOperation(plan.op)
|
|
318
325
|
? vendorRefusal(err, requestSecrets(ctx)) : undefined;
|
|
319
|
-
const code =
|
|
326
|
+
const code = shapeOnlyVendorCode(plan.op, c.httpStatus, err) ?? c.code;
|
|
320
327
|
entry = { ...base, state: c.state, at: now(), outcome: { code, retryable: c.retryable, ...(c.httpStatus !== undefined ? { httpStatus: c.httpStatus } : {}), ...(said !== undefined ? { vendorMessage: said } : {}) } };
|
|
321
328
|
}
|
|
322
329
|
}
|
|
@@ -364,10 +371,9 @@ function recordResult(a, entry, confirmation) {
|
|
|
364
371
|
/** Waits before each re-read of an update whose first read-back looks stale (#184); tests set it to zeros. */
|
|
365
372
|
export const READBACK_RECHECK = { delaysMs: [750, 1500] };
|
|
366
373
|
/**
|
|
367
|
-
* Record
|
|
368
|
-
*
|
|
369
|
-
*
|
|
370
|
-
* answer instead of letting a replay quietly answer plain ok.
|
|
374
|
+
* Record read-back verification as a later ledger line (the latest line wins on replay).
|
|
375
|
+
* Wait briefly for a concurrent apply to release the op lock. Return false if the result
|
|
376
|
+
* could not be recorded.
|
|
371
377
|
*/
|
|
372
378
|
export async function recordMiss(store, entry, attempts = 10, waitMs = 100) {
|
|
373
379
|
for (let i = 0; i < attempts; i += 1) {
|
|
@@ -385,9 +391,46 @@ export async function recordMiss(store, entry, attempts = 10, waitMs = 100) {
|
|
|
385
391
|
}
|
|
386
392
|
return false;
|
|
387
393
|
}
|
|
394
|
+
function inventoryLocationMisses(sent, stored, id) {
|
|
395
|
+
if (stored === null || typeof stored !== 'object' || !Object.hasOwn(stored, 'id') || stored.id !== id) {
|
|
396
|
+
throw new Error('Inventory location read-back did not match the expected ID');
|
|
397
|
+
}
|
|
398
|
+
if (sent === null || typeof sent !== 'object')
|
|
399
|
+
return [];
|
|
400
|
+
const submitted = sent;
|
|
401
|
+
const persisted = stored;
|
|
402
|
+
return Object.keys(submitted).filter(field => !Object.hasOwn(persisted, field) || submitted[field] !== persisted[field]);
|
|
403
|
+
}
|
|
404
|
+
async function recordReadBack(a, entry) {
|
|
405
|
+
try {
|
|
406
|
+
if (await recordMiss(a.store, entry))
|
|
407
|
+
return true;
|
|
408
|
+
}
|
|
409
|
+
catch {
|
|
410
|
+
// The read-back is already known even if the ledger write fails.
|
|
411
|
+
}
|
|
412
|
+
a.ctx.log.warn('Write read-back verification could not be recorded in the ledger', { op: a.plan.op });
|
|
413
|
+
return false;
|
|
414
|
+
}
|
|
415
|
+
async function reportPersistedMiss(a, entry, fields, record) {
|
|
416
|
+
const missedEntry = { ...entry, outcome: { ...entry.outcome, code: 'FIELD_NOT_PERSISTED', fields } };
|
|
417
|
+
const recorded = await recordReadBack(a, missedEntry);
|
|
418
|
+
return notPersistedAnswer(a.plan, missedEntry, fields, { replayed: false, record, unrecorded: !recorded });
|
|
419
|
+
}
|
|
420
|
+
async function reportVerifiedReadBack(a, entry, record) {
|
|
421
|
+
const extra = { replayed: false, data: { record: record ?? null } };
|
|
422
|
+
if (entry.outcome?.code !== 'READBACK_UNVERIFIED')
|
|
423
|
+
return outcomeAnswer(a.plan, entry, extra);
|
|
424
|
+
const verified = { ...entry, outcome: { id: entry.outcome.id } };
|
|
425
|
+
const recorded = await recordReadBack(a, verified);
|
|
426
|
+
return outcomeAnswer(a.plan, verified, {
|
|
427
|
+
...extra,
|
|
428
|
+
...(recorded ? {} : { summary: 'The write was verified, but verification could not be recorded in the ledger. A replay may still report an unverified result. Do not resend the write.' }),
|
|
429
|
+
});
|
|
430
|
+
}
|
|
388
431
|
/** Answer from the recorded entry: failures, moves, and the read-backs of creates and updates. */
|
|
389
432
|
async function respond(a, r) {
|
|
390
|
-
const { ctx,
|
|
433
|
+
const { ctx, plan } = a;
|
|
391
434
|
const { record, shape, entry, error, moveResult, callResult } = r;
|
|
392
435
|
if (entry.state !== 'succeeded') {
|
|
393
436
|
const secrets = requestSecrets(ctx);
|
|
@@ -410,9 +453,16 @@ async function respond(a, r) {
|
|
|
410
453
|
projectRaw = (result) => projectTimeEntryVerification(result, id);
|
|
411
454
|
}
|
|
412
455
|
const back = await readOneItem(ctx, `${record.resource}.get`, getIds(ctx, record.resource, plan.targets.parentId, id), undefined, { fresh: true }, projectRaw);
|
|
413
|
-
|
|
456
|
+
if (entry.outcome.code === 'READBACK_UNVERIFIED') {
|
|
457
|
+
const missed = inventoryLocationMisses(plan.args.at(-1), back.result, id);
|
|
458
|
+
if (missed.length > 0)
|
|
459
|
+
return await reportPersistedMiss(a, entry, missed, back.result);
|
|
460
|
+
}
|
|
461
|
+
return await reportVerifiedReadBack(a, entry, back.result);
|
|
414
462
|
}
|
|
415
463
|
catch (err) {
|
|
464
|
+
if (entry.outcome.code === 'READBACK_UNVERIFIED')
|
|
465
|
+
return outcomeAnswer(plan, entry, { replayed: false });
|
|
416
466
|
const code = String(typedErrorPayload(err, ctx.correlationId).code);
|
|
417
467
|
return outcomeAnswer(plan, entry, {
|
|
418
468
|
replayed: false,
|
|
@@ -436,8 +486,13 @@ async function respond(a, r) {
|
|
|
436
486
|
let back = await readBack();
|
|
437
487
|
let missed = [];
|
|
438
488
|
for (let i = 0;; i++) {
|
|
439
|
-
|
|
440
|
-
|
|
489
|
+
if (record.id === 'inventory_locations.update') {
|
|
490
|
+
missed = inventoryLocationMisses(sent, back.result, id);
|
|
491
|
+
}
|
|
492
|
+
else {
|
|
493
|
+
const stored = back.result !== null && typeof back.result === 'object' ? stripUntrustedDeep(back.result) : undefined;
|
|
494
|
+
missed = stored === undefined || sent === null || typeof sent !== 'object' ? [] : notPersistedFields(sent, stored);
|
|
495
|
+
}
|
|
441
496
|
const delay = READBACK_RECHECK.delaysMs[i];
|
|
442
497
|
if (missed.length === 0 || delay === undefined)
|
|
443
498
|
break;
|
|
@@ -445,15 +500,13 @@ async function respond(a, r) {
|
|
|
445
500
|
back = await readBack();
|
|
446
501
|
}
|
|
447
502
|
if (missed.length === 0)
|
|
448
|
-
return
|
|
503
|
+
return await reportVerifiedReadBack(a, entry, back.result);
|
|
449
504
|
// record the miss: the latest ledger line wins, so a replay answers the same reasons.
|
|
450
|
-
|
|
451
|
-
const recorded = await recordMiss(store, missedEntry);
|
|
452
|
-
if (!recorded)
|
|
453
|
-
ctx.log.warn('FIELD_NOT_PERSISTED could not be recorded in the ledger (op lock busy)', { op: plan.op });
|
|
454
|
-
return notPersistedAnswer(plan, missedEntry, missed, { replayed: false, record: back.result ?? null, unrecorded: !recorded });
|
|
505
|
+
return await reportPersistedMiss(a, entry, missed, back.result ?? null);
|
|
455
506
|
}
|
|
456
507
|
catch (err) {
|
|
508
|
+
if (entry.outcome?.code === 'READBACK_UNVERIFIED')
|
|
509
|
+
return outcomeAnswer(plan, entry, { replayed: false });
|
|
457
510
|
const code = String(typedErrorPayload(err, ctx.correlationId).code);
|
|
458
511
|
return outcomeAnswer(plan, entry, {
|
|
459
512
|
replayed: false,
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { COOLDOWN_MINUTES } from '../../write/store.js';
|
|
2
2
|
import { answer, applyToolFor, reason } from './common.js';
|
|
3
|
-
import {
|
|
3
|
+
import { isShapeOnlyVendorOperation, stripThenScrub } from '../results/errors.js';
|
|
4
4
|
import { cleanUntrustedText } from '../results/untrusted.js';
|
|
5
5
|
// ---------------------------------------------------------------------------
|
|
6
6
|
// autotask_apply: the execution
|
|
@@ -48,14 +48,20 @@ export function vendorRefusal(err, secrets) {
|
|
|
48
48
|
/** The envelope of an update whose HTTP write succeeded but whose stored record lacks some sent fields (issue #103). */
|
|
49
49
|
export function notPersistedAnswer(plan, entry, fields, extra) {
|
|
50
50
|
const resource = plan.targets.resource;
|
|
51
|
-
|
|
51
|
+
const created = plan.facts.shape.startsWith('create');
|
|
52
|
+
const names = fields.join(', ');
|
|
53
|
+
const evidence = extra.record === undefined ? 'Re-read the record to see what is stored' : 'The stored record is in data.record';
|
|
54
|
+
const detail = created
|
|
55
|
+
? `Autotask created the record, and the read-back differed from the approved values for ${names}. ${evidence}. Review the stored record before making another change.`
|
|
56
|
+
: `the vendor accepted the update but did not apply: ${names}. ${evidence}; the field was still unchanged after repeated re-reads, so the vendor appears not to support changing it on ${resource}. Re-read the record once more later before repeating the update.`;
|
|
57
|
+
return answer('error', 'stop', [reason('FIELD_NOT_PERSISTED', detail, fields[0])], {
|
|
52
58
|
operation: plan.op,
|
|
53
59
|
targets: plan.targets,
|
|
54
60
|
outcome: 'succeeded',
|
|
55
61
|
result: entry.outcome?.id === undefined ? {} : { id: entry.outcome.id },
|
|
56
62
|
...(extra.record === undefined ? {} : { record: extra.record }),
|
|
57
63
|
notPersisted: fields,
|
|
58
|
-
}, { plan: plan.handle, planHash: plan.planHash, ...(extra.replayed ? { replayed: true } : {}), summary: `${plan.op} reached the vendor (HTTP success) but ${
|
|
64
|
+
}, { plan: plan.handle, planHash: plan.planHash, ...(extra.replayed ? { replayed: true } : {}), summary: `${plan.op} ${created ? `created the record, and its read-back differed for ${names}.` : `reached the vendor (HTTP success) but ${names} did not change.`}${extra.unrecorded === true ? ' The verification result could not be recorded. Re-read the record before relying on a replay.' : ''}` });
|
|
59
65
|
}
|
|
60
66
|
/** The envelope for a recorded (or just recorded) outcome. `result` overrides the ledger id a success reports. */
|
|
61
67
|
export function outcomeAnswer(plan, entry, extra) {
|
|
@@ -64,6 +70,9 @@ export function outcomeAnswer(plan, entry, extra) {
|
|
|
64
70
|
if (entry.state === 'succeeded' && entry.outcome?.code === 'FIELD_NOT_PERSISTED' && entry.outcome.fields !== undefined) {
|
|
65
71
|
return notPersistedAnswer(plan, entry, entry.outcome.fields, { replayed: extra.replayed });
|
|
66
72
|
}
|
|
73
|
+
if (entry.state === 'succeeded' && entry.outcome?.code === 'READBACK_UNVERIFIED') {
|
|
74
|
+
return answer('error', 'stop', [reason('WRITE_OUTCOME_UNKNOWN', 'Autotask returned a write receipt. Read-back verification is pending or unavailable. Read the record at data.result.id before making another change. Do not resend the write.')], { ...base, result: { id: entry.outcome.id } }, meta);
|
|
75
|
+
}
|
|
67
76
|
if (entry.state === 'succeeded' && entry.outcome?.sourceId !== undefined) {
|
|
68
77
|
// a move: old id -> new id (the SDK result is the verification: no extra read-back)
|
|
69
78
|
const manual = entry.outcome.code === 'MOVE_MANUAL_DELETE';
|
|
@@ -99,7 +108,7 @@ export function outcomeAnswer(plan, entry, extra) {
|
|
|
99
108
|
},
|
|
100
109
|
};
|
|
101
110
|
}
|
|
102
|
-
else if (extra.replayed && !retryable && (said !== undefined ||
|
|
111
|
+
else if (extra.replayed && !retryable && (said !== undefined || isShapeOnlyVendorOperation(plan.op)) && !('error' in base)) {
|
|
103
112
|
data = { ...base, error: { error: true, code: entry.outcome?.code ?? 'WRITE_FAILED', ...(entry.outcome?.httpStatus !== undefined ? { httpStatus: entry.outcome.httpStatus } : {}), retryable: false, nextAction: 'stop', suggestedAction: refusedAction(said ?? '') } };
|
|
104
113
|
}
|
|
105
114
|
const failureCode = forbidden ? 'FORBIDDEN' : entry.outcome?.code ?? 'error';
|
|
@@ -29,7 +29,7 @@ export declare function sanitisedArtefact(value: unknown, path: string, depth?:
|
|
|
29
29
|
* rules), so this server can never undo a create or a delete.
|
|
30
30
|
* An update keeps the SDK's answer, including irreversible cancellation.
|
|
31
31
|
*/
|
|
32
|
-
export declare function honestImpact(impact: unknown, shape: WriteShape): unknown;
|
|
32
|
+
export declare function honestImpact(impact: unknown, shape: WriteShape, deleteBoundary?: unknown): unknown;
|
|
33
33
|
/**
|
|
34
34
|
* Strip control and bidi characters and NFC-normalise every string in a write payload (never
|
|
35
35
|
* capped). NFC runs after the strip (issue 59): the vendor stores a decomposed accent (an `e` plus
|
|
@@ -72,10 +72,13 @@ export function sanitisedArtefact(value, path, depth = 0) {
|
|
|
72
72
|
* rules), so this server can never undo a create or a delete.
|
|
73
73
|
* An update keeps the SDK's answer, including irreversible cancellation.
|
|
74
74
|
*/
|
|
75
|
-
export function honestImpact(impact, shape) {
|
|
75
|
+
export function honestImpact(impact, shape, deleteBoundary) {
|
|
76
76
|
if (impact === null || typeof impact !== 'object' || Array.isArray(impact) || shape.startsWith('update'))
|
|
77
77
|
return impact;
|
|
78
|
-
|
|
78
|
+
const note = deleteBoundary?.note;
|
|
79
|
+
const reversibleNote = shape.startsWith('create') && typeof note === 'string' ? note
|
|
80
|
+
: 'This server never runs deletes unattended: undoing it needs a person in Autotask.';
|
|
81
|
+
return { ...impact, reversible: false, reversibleNote };
|
|
79
82
|
}
|
|
80
83
|
/**
|
|
81
84
|
* Strip control and bidi characters and NFC-normalise every string in a write payload (never
|
|
@@ -143,7 +143,7 @@ function describe(record, shape, op, parsed, dry) {
|
|
|
143
143
|
const t = parsed.targets;
|
|
144
144
|
const ids = [t.parentId, t.id, t.toId].filter((v) => v !== undefined);
|
|
145
145
|
const data = shape === 'call' ? Object.fromEntries(Object.keys(record.inputSchema).map((k, i) => [k, parsed.args[i]])) : dry.data;
|
|
146
|
-
const impact = shape === 'call' ? CALL_IMPACT : (honestImpact(dry.impact, shape) ?? { scope: 'single', affected: 1, reversible: !shape.startsWith('delete') });
|
|
146
|
+
const impact = shape === 'call' ? CALL_IMPACT : (honestImpact(dry.impact, shape, record.metadata.deleteBoundary) ?? { scope: 'single', affected: 1, reversible: !shape.startsWith('delete') });
|
|
147
147
|
const full = { operation: op, target: { resource: t.resource, ids }, request: { method: '', path: '' }, checks: [], warnings: [], simulated: true, ...dry, wouldApply: dry.wouldApply ?? true, impact, data };
|
|
148
148
|
return describeWrite(full, record);
|
|
149
149
|
}
|
|
@@ -181,7 +181,7 @@ function evaluatePreview(r, a, snap, dry, resource, types) {
|
|
|
181
181
|
hazards: decision.hazards,
|
|
182
182
|
diff: markedDiff(dry.diff, types),
|
|
183
183
|
warnings: (dry.warnings ?? []).slice(0, 20).map((x) => String(x)),
|
|
184
|
-
impact: shape === 'call' ? CALL_IMPACT : honestImpact(dry.impact, shape),
|
|
184
|
+
impact: shape === 'call' ? CALL_IMPACT : honestImpact(dry.impact, shape, record.metadata.deleteBoundary),
|
|
185
185
|
// #183 AC21: the body a create will send — the SDK-redacted dry-run `data` (never the raw
|
|
186
186
|
// parsed args: they still carry pre-redaction personal-data values), so a gated create on a
|
|
187
187
|
// DELETE-less resource confirms the exact body it approves.
|
|
@@ -111,7 +111,9 @@ function createReader(ctx, targetKey, signal, operation) {
|
|
|
111
111
|
const articleCategory = articleWrite && resource === 'knowledge_base_categories';
|
|
112
112
|
const knowledgeBaseRecord = (articleWrite && resource === 'knowledge_base_articles')
|
|
113
113
|
|| (resource === 'knowledge_base_categories' && (categoryWrite || articleCategory));
|
|
114
|
-
|
|
114
|
+
const inventoryLocation = operation === 'inventory_locations.update' && resource === 'inventory_locations';
|
|
115
|
+
if ((knowledgeBaseRecord || inventoryLocation) && (model === null || typeof model !== 'object' || Array.isArray(model)
|
|
116
|
+
|| (inventoryLocation && !Object.hasOwn(model, 'id'))
|
|
115
117
|
|| asIdOrZero(ci(model, 'id')) !== ids.at(-1))) {
|
|
116
118
|
throw new SnapshotScopeUnresolved(`${resource}: the fresh record did not establish the requested identity`);
|
|
117
119
|
}
|
|
@@ -20,16 +20,15 @@ export declare function readJsonl<T>(path: string): {
|
|
|
20
20
|
/** Rewrite a JSONL file atomically (0600, fsync, rename). */
|
|
21
21
|
export declare function rewriteJsonl(path: string, rows: unknown[]): void;
|
|
22
22
|
/**
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
* what makes the boot-rewrite rename safe for every process (no persistent fd to orphan).
|
|
23
|
+
* Append one checked O_APPEND write under the caller's op lock. Preserve a complete legacy
|
|
24
|
+
* tail even if its newline was lost. The per-append close lets the boot rewrite safely rename.
|
|
26
25
|
*/
|
|
27
26
|
export declare function appendJsonl(path: string, row: unknown): void;
|
|
28
27
|
/**
|
|
29
28
|
* A fresh scan of a JSONL file (issue #68: the file is the single source of truth). Tolerates a
|
|
30
|
-
* torn
|
|
31
|
-
*
|
|
32
|
-
*
|
|
29
|
+
* torn final line (a peer crashed mid-append, or this read raced one). Re-read an invalid final
|
|
30
|
+
* line once and skip it if still bad. Complete JSON without a final newline remains visible
|
|
31
|
+
* because older writers could have acted on the row. The boot rewrite counts bad lines.
|
|
33
32
|
* A bad line anywhere else is skipped here and counted at the next boot.
|
|
34
33
|
*/
|
|
35
34
|
export declare function scanJsonl<T>(path: string): T[];
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/** Small file helpers: JSONL read/scan/append/rewrite, the state key, the kill file, handles (issue #88). */
|
|
2
2
|
import { randomBytes } from 'node:crypto';
|
|
3
|
-
import { closeSync, existsSync, fsyncSync, openSync, readFileSync, renameSync, statSync, writeSync } from 'node:fs';
|
|
3
|
+
import { closeSync, existsSync, fstatSync, fsyncSync, ftruncateSync, openSync, readFileSync, readSync, renameSync, statSync, writeSync } from 'node:fs';
|
|
4
4
|
import { ConfigError } from '../../config/schema.js';
|
|
5
5
|
import { OP_LOCK_POLL_MS } from './constants.js';
|
|
6
6
|
export const LOOSE_MODE = 0o077;
|
|
@@ -69,24 +69,58 @@ export function readJsonl(path) {
|
|
|
69
69
|
}
|
|
70
70
|
return { rows, bad };
|
|
71
71
|
}
|
|
72
|
+
function writeComplete(fd, text) {
|
|
73
|
+
const bytes = Buffer.from(text);
|
|
74
|
+
if (writeSync(fd, bytes) !== bytes.length)
|
|
75
|
+
throw new Error('Incomplete JSONL write');
|
|
76
|
+
}
|
|
72
77
|
/** Rewrite a JSONL file atomically (0600, fsync, rename). */
|
|
73
78
|
export function rewriteJsonl(path, rows) {
|
|
74
79
|
const tmp = `${path}.tmp`;
|
|
75
80
|
const fd = openSync(tmp, 'w', 0o600);
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
81
|
+
try {
|
|
82
|
+
writeComplete(fd, rows.map((r) => `${JSON.stringify(r)}\n`).join(''));
|
|
83
|
+
fsyncSync(fd);
|
|
84
|
+
}
|
|
85
|
+
finally {
|
|
86
|
+
closeSync(fd);
|
|
87
|
+
}
|
|
79
88
|
renameSync(tmp, path);
|
|
80
89
|
}
|
|
81
90
|
/**
|
|
82
|
-
*
|
|
83
|
-
*
|
|
84
|
-
* what makes the boot-rewrite rename safe for every process (no persistent fd to orphan).
|
|
91
|
+
* Append one checked O_APPEND write under the caller's op lock. Preserve a complete legacy
|
|
92
|
+
* tail even if its newline was lost. The per-append close lets the boot rewrite safely rename.
|
|
85
93
|
*/
|
|
86
94
|
export function appendJsonl(path, row) {
|
|
87
|
-
const
|
|
95
|
+
const line = `${JSON.stringify(row)}\n`;
|
|
96
|
+
const fd = openSync(path, 'a+', 0o600);
|
|
88
97
|
try {
|
|
89
|
-
|
|
98
|
+
let { size } = fstatSync(fd);
|
|
99
|
+
let prefix = '';
|
|
100
|
+
if (size > 0) {
|
|
101
|
+
const tail = Buffer.alloc(1);
|
|
102
|
+
if (readSync(fd, tail, 0, 1, size - 1) !== 1)
|
|
103
|
+
throw new Error('Could not read the JSONL tail');
|
|
104
|
+
if (tail[0] !== 0x0a) {
|
|
105
|
+
const contents = readFileSync(path);
|
|
106
|
+
const boundary = contents.lastIndexOf(0x0a) + 1;
|
|
107
|
+
try {
|
|
108
|
+
JSON.parse(contents.subarray(boundary).toString('utf8'));
|
|
109
|
+
prefix = '\n'; // A previous release may have accepted and acted on this complete row.
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
ftruncateSync(fd, boundary);
|
|
113
|
+
size = boundary;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
try {
|
|
118
|
+
writeComplete(fd, prefix + line);
|
|
119
|
+
}
|
|
120
|
+
catch (err) {
|
|
121
|
+
ftruncateSync(fd, size);
|
|
122
|
+
throw err;
|
|
123
|
+
}
|
|
90
124
|
fsyncSync(fd);
|
|
91
125
|
}
|
|
92
126
|
finally {
|
|
@@ -95,9 +129,9 @@ export function appendJsonl(path, row) {
|
|
|
95
129
|
}
|
|
96
130
|
/**
|
|
97
131
|
* A fresh scan of a JSONL file (issue #68: the file is the single source of truth). Tolerates a
|
|
98
|
-
* torn
|
|
99
|
-
*
|
|
100
|
-
*
|
|
132
|
+
* torn final line (a peer crashed mid-append, or this read raced one). Re-read an invalid final
|
|
133
|
+
* line once and skip it if still bad. Complete JSON without a final newline remains visible
|
|
134
|
+
* because older writers could have acted on the row. The boot rewrite counts bad lines.
|
|
101
135
|
* A bad line anywhere else is skipped here and counted at the next boot.
|
|
102
136
|
*/
|
|
103
137
|
export function scanJsonl(path) {
|
|
@@ -72,7 +72,7 @@ export function createLedger({ ledgerPath }) {
|
|
|
72
72
|
// have changed the file, so a caught error must never expose an older view.
|
|
73
73
|
rows = undefined;
|
|
74
74
|
// The stamp is what the boot rewrite reads back: which `sending` lines belong to live
|
|
75
|
-
// holders (issue #68). One O_APPEND line: open, write, fsync, close.
|
|
75
|
+
// holders (issue #68). One checked O_APPEND line: open, write, fsync, close.
|
|
76
76
|
appendJsonl(ledgerPath, { ...entry, boot: BOOT_ID, pid: process.pid });
|
|
77
77
|
},
|
|
78
78
|
counters(op, at) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "iit-mcp-autotask",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.64.0",
|
|
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.91.0",
|
|
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.
|
|
3
|
+
"version": "0.64.0",
|
|
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.91.0"
|
|
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"
|