iit-mcp-autotask 0.58.0 → 0.58.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -797,3 +797,83 @@ For token rotation, two hashes may name the same principal only with identical c
797
797
  ### Complete time-entry note verification
798
798
 
799
799
  `autotask_read {operation:"time_entries.get", args:[id], projection:"time_entry_verification_v1"}` returns one forced-fresh read snapshot: scalar time-entry fields and versioned SHA256/code-point/UTF-8-byte metadata for `summaryNotes` and `internalNotes`. It never returns note bodies or changes the normal free-text caps. Hashes cover exact raw UTF-8, without whitespace, wrapper or line-ending normalisation; null and unavailable fields are distinct. Each note is bounded at 1 MiB; unsupported, missing, oversized or malformed data is never proof of equality. Callers must check the contract, fresh flag and entry/resource identity before comparing. Existing credentials and read policy still apply.
800
+
801
+ For consumers that reserve a vendor-call budget, `autotask_tenant_status` with
802
+ `parts:["server"]` exposes zero-vendor `server.readRuntime` proof of the actual client
803
+ retry/recovery bounds. Pass its `sha256` as `autotask_read.expectedReadRuntime` on
804
+ every read to refuse changed or unavailable bounds before dispatch. Validate the
805
+ contract, SDK/plan and supported bounds first; retain separate connection/auth pins.
806
+ See [the runtime proof contract](docs/read-runtime.md) for canonicalization, drift
807
+ semantics and typed refusals. The guard is optional for existing consumers.
808
+
809
+ For full bounded note display and protected-field evidence, opt in to `billing_review_entry_v1`:
810
+
811
+ ```json
812
+ {"operation":"time_entries.get","args":[44],"projection":"billing_review_entry_v1"}
813
+ {"operation":"time_entries.query","args":[{"filter":[{"field":"resourceID","op":"eq","value":7},{"field":"id","op":"gt","value":0}],"limit":25}],"projection":"billing_review_entry_v1"}
814
+ ```
815
+
816
+ This versioned projection accepts one positive numeric get ID or one query bag containing only a
817
+ nonempty SDK `filter` and optional integer `limit` (default/max 25). Batches, `includeFields`, `walk`,
818
+ `latest`, and note capping are refused. Conditions use only exact, unqualified built-in scalar names
819
+ from the closed `entry` snapshot below, including inside AND/OR groups. Wrappers, prefixes/relation
820
+ fields, case aliases, whitespace, unsafe characters, note fields and UDF conditions are refused before
821
+ vendor work. Operators must also use their exact canonical SDK spelling, without wrappers.
822
+ Resolve company scope to ticket IDs separately, then filter by `ticketID`/`resourceID`.
823
+ Generic reads retain the full SDK filter grammar. The projection adds `ticketID gt 0` and refuses
824
+ non-ticket/task rows. No initial date cutoff is added.
825
+
826
+ The closed result is `{contract:"billing-review-entry-v1", fresh:true, items, paging}`. Each item is
827
+ `{state:"complete", entry, notes, evidence}` or `{state:"unavailable", id, resourceID, ticketID, reason}`.
828
+ The closed `entry` includes every SDK time-entry scalar except note bodies: all four editable fields
829
+ are represented by `billingCodeID`, `contractID`, and the two `notes` records. Reference, role, time,
830
+ hours/offset, invoice/nonbillable, internal billing, service/bundle, approval, creator/updater and
831
+ modified fields must all be present with valid types (nullable nonessential fields are accepted).
832
+ Explicit NULL `startDateTime`/`endDateTime` values are retained for hours-only ticket entries, as allowed
833
+ by the [vendor TimeEntries contract](https://webservices.autotask.net/help/developerhelp/Content/APIs/REST/Entities/TimeEntriesEntity.htm).
834
+ Both keys must still be present; `dateWorked` and finite `hoursWorked` remain required. NULL clock
835
+ fields remain protected by the digests, and callers cannot infer an overlap interval when absent.
836
+ Missing/invalid fields cannot produce complete evidence. Unknown returned fields are hashed but never
837
+ returned. Invalid identities, scope or paging fail the whole call, without echoing the source record.
838
+
839
+ String notes carry `{state:"complete", display, units, characters, bytes, sha256, displayChanged}`;
840
+ NULL carries `{state:"null", display:null}`. Lengths and SHA256 describe exact raw UTF-8 before cleaning:
841
+ UTF-16 units, Unicode code points and UTF-8 bytes respectively. Lone surrogates are refused.
842
+ `display` remains untrusted: unsafe controls are stripped and wrapper forgeries normalized, with full
843
+ bounded prose instead of the normal 500-character cap. `displayChanged` compares raw text with the
844
+ displayed content excluding the server's wrapper; it includes literal-wrapper neutralization and
845
+ stripping. Display text is never evidence of original bytes. Callers should refuse deterministic note
846
+ edits when normalization prevents preserving the original. An unsupported/oversized note makes only
847
+ that entry unavailable; the row and its position remain in the page.
848
+
849
+ `evidence` contains `canonicalization:"billing-review-json-v1"`, `sourceSha256` and `protectedSha256`.
850
+ The source is the entire raw API record, including unknown fields, rather than wire JSON bytes.
851
+ Canonicalization sorts object keys by UTF-16 order, uses JavaScript JSON string/finite-number encoding,
852
+ preserves array order, and rejects unsupported values, accessors, non-plain objects and invalid Unicode.
853
+ Protected evidence excludes **only** `summaryNotes`, `internalNotes`, `billingCodeID`, `contractID` and
854
+ `lastModifiedDateTime`; all other audit/financial/time/reference and unknown fields remain protected.
855
+ Compare these digests as opaque strings; do not recreate JavaScript numeric encoding in another language.
856
+
857
+ Bounds: each note is at most 32,000 UTF-16 units / 96,000 UTF-8 bytes; each canonical record is at most
858
+ 1,048,576 encoded bytes, depth 16 (root depth 0), and 4,096 visited values/own keys per container.
859
+ Each query filter is at most 8,000 canonical UTF-8 bytes. The complete sanitized tool result, including
860
+ its structured data and mirrored text, must fit 4,194,304 UTF-8 bytes; retry the same cursor with a smaller
861
+ limit if it does not. No row is silently removed to fit a cap.
862
+
863
+ `paging` contains `fetched`, `hasMore`, `pagesWalked`, and `nextAfterId` (the last ID when more remain,
864
+ otherwise NULL). Returned IDs must be strictly increasing, above the supplied top-level `id gt`
865
+ bound, with matching counts and no partial/capped/scope markers. Resume by retaining the same scope
866
+ filter and adding/updating a top-level `id gt nextAfterId` condition. `hasMore:false` describes this
867
+ query's current transport exhaustion; callers still check every entry's state and their billing rules.
868
+ Validation covers only the exposed SDK `BoundedQueryResult`. SDK 0.60 discards unknown outer vendor
869
+ response-envelope metadata; this projection cannot inspect discarded metadata or establish tenant-wide
870
+ completeness. Top-level identity equality and `id gt` conditions accept safe non-negative integer
871
+ numbers or decimal digit strings (surrounding whitespace is ignored); returned row IDs remain strictly
872
+ numeric. Identity values normalize recursively, including inside groups. Local row-level identity
873
+ re-checks cover top-level conjunctive predicates; the SDK/API enforces nested Boolean filtering.
874
+ Bounds inside OR groups are not applied globally.
875
+ GET uses the SDK forced-fresh option; queries execute live because the SDK query path is uncached
876
+ (the get-only fresh option is omitted). Server-owned `names:false` avoids derived label expansion.
877
+ A call may still need SDK metadata/relation requests or multiple vendor pages; the 25-row bound
878
+ is a returned-row cap, not a promise of one vendor request. No projection adds a server read cache or
879
+ changes the legacy metadata-only projection.
@@ -0,0 +1,14 @@
1
+ export declare const BILLING_RECORD_MAX_BYTES = 1048576;
2
+ export declare const BILLING_RECORD_MAX_DEPTH = 16;
3
+ export declare const BILLING_RECORD_MAX_NODES = 4096;
4
+ export declare const BILLING_NOTE_MAX_UNITS = 32000;
5
+ export declare const BILLING_NOTE_MAX_BYTES = 96000;
6
+ export declare class EvidenceUnavailable extends Error {
7
+ readonly reason: string;
8
+ constructor(reason: string);
9
+ }
10
+ export declare function plainRecord(value: unknown): value is Record<string, unknown>;
11
+ export declare function sha256(value: string): string;
12
+ /** Sorted UTF-16 keys, JSON string/finite-number encoding, no toJSON/accessors/prototype traversal. */
13
+ export declare function canonicalRecord(row: Record<string, unknown>, protectedOnly?: boolean): string;
14
+ export declare function noteEvidence(value: unknown): Record<string, unknown>;
@@ -0,0 +1,127 @@
1
+ /** Bounded canonical evidence for raw API records; hashes are opaque to callers. */
2
+ import { createHash } from 'node:crypto';
3
+ import { cleanUntrustedText, outerUnwrap, wrapOrSelf } from './results/untrusted.js';
4
+ export const BILLING_RECORD_MAX_BYTES = 1_048_576;
5
+ export const BILLING_RECORD_MAX_DEPTH = 16;
6
+ export const BILLING_RECORD_MAX_NODES = 4096;
7
+ export const BILLING_NOTE_MAX_UNITS = 32_000;
8
+ export const BILLING_NOTE_MAX_BYTES = 96_000;
9
+ const EDITABLE = new Set(['summaryNotes', 'internalNotes', 'billingCodeID', 'contractID', 'lastModifiedDateTime']);
10
+ export class EvidenceUnavailable extends Error {
11
+ reason;
12
+ constructor(reason) {
13
+ super(reason);
14
+ this.reason = reason;
15
+ }
16
+ }
17
+ export function plainRecord(value) {
18
+ return value !== null && typeof value === 'object' && !Array.isArray(value) && [Object.prototype, null].includes(Object.getPrototypeOf(value));
19
+ }
20
+ function text(value) {
21
+ // UTF-16 units lower-bound UTF-8 bytes; put() enforces the exact encoded record budget.
22
+ if (value.length > BILLING_RECORD_MAX_BYTES)
23
+ throw new EvidenceUnavailable('record_too_large');
24
+ if (/[\uD800-\uDFFF]/u.test(value))
25
+ throw new EvidenceUnavailable('invalid_unicode');
26
+ }
27
+ export function sha256(value) { return createHash('sha256').update(value, 'utf8').digest('hex'); }
28
+ /** Sorted UTF-16 keys, JSON string/finite-number encoding, no toJSON/accessors/prototype traversal. */
29
+ export function canonicalRecord(row, protectedOnly = false) {
30
+ let bytes = 0;
31
+ let nodes = 0;
32
+ const parts = [];
33
+ const put = (part) => {
34
+ bytes += Buffer.byteLength(part, 'utf8');
35
+ if (bytes > BILLING_RECORD_MAX_BYTES)
36
+ throw new EvidenceUnavailable('record_too_large');
37
+ parts.push(part);
38
+ };
39
+ const walk = (value, depth) => {
40
+ if (++nodes > BILLING_RECORD_MAX_NODES)
41
+ throw new EvidenceUnavailable('record_too_many_nodes');
42
+ if (depth > BILLING_RECORD_MAX_DEPTH)
43
+ throw new EvidenceUnavailable('record_too_deep');
44
+ if (value === null || typeof value === 'boolean') {
45
+ put(JSON.stringify(value));
46
+ return;
47
+ }
48
+ if (typeof value === 'number' && Number.isFinite(value)) {
49
+ put(JSON.stringify(value));
50
+ return;
51
+ }
52
+ if (typeof value === 'string') {
53
+ text(value);
54
+ put(JSON.stringify(value));
55
+ return;
56
+ }
57
+ if (!Array.isArray(value) && !plainRecord(value))
58
+ throw new EvidenceUnavailable('unsupported_value');
59
+ if (Object.getOwnPropertySymbols(value).length > 0)
60
+ throw new EvidenceUnavailable('unsupported_value');
61
+ if (Array.isArray(value) && value.length > BILLING_RECORD_MAX_NODES)
62
+ throw new EvidenceUnavailable('record_too_many_nodes');
63
+ const keys = Object.getOwnPropertyNames(value);
64
+ if (keys.length > BILLING_RECORD_MAX_NODES)
65
+ throw new EvidenceUnavailable('record_too_many_nodes');
66
+ if (Array.isArray(value)) {
67
+ if (Object.getPrototypeOf(value) !== Array.prototype)
68
+ throw new EvidenceUnavailable('unsupported_array');
69
+ if (value.length > BILLING_RECORD_MAX_NODES || keys.length !== value.length + 1)
70
+ throw new EvidenceUnavailable('unsupported_array');
71
+ put('[');
72
+ for (let i = 0; i < value.length; i++) {
73
+ const d = Object.getOwnPropertyDescriptor(value, String(i));
74
+ if (d === undefined || !('value' in d) || !d.enumerable)
75
+ throw new EvidenceUnavailable('unsupported_value');
76
+ if (i > 0)
77
+ put(',');
78
+ walk(d.value, depth + 1);
79
+ }
80
+ put(']');
81
+ return;
82
+ }
83
+ let keyUnits = 0;
84
+ for (const key of keys) {
85
+ keyUnits += key.length;
86
+ if (keyUnits > BILLING_RECORD_MAX_BYTES)
87
+ throw new EvidenceUnavailable('record_too_large');
88
+ text(key);
89
+ }
90
+ put('{');
91
+ let first = true;
92
+ for (const key of keys.sort()) {
93
+ const d = Object.getOwnPropertyDescriptor(value, key);
94
+ if (!('value' in d) || !d.enumerable)
95
+ throw new EvidenceUnavailable('unsupported_value');
96
+ if (depth === 0 && protectedOnly && EDITABLE.has(key))
97
+ continue;
98
+ if (!first)
99
+ put(',');
100
+ first = false;
101
+ put(JSON.stringify(key));
102
+ put(':');
103
+ walk(d.value, depth + 1);
104
+ }
105
+ put('}');
106
+ };
107
+ walk(row, 0);
108
+ return parts.join('');
109
+ }
110
+ export function noteEvidence(value) {
111
+ if (value === null)
112
+ return { state: 'null', display: null };
113
+ if (typeof value !== 'string')
114
+ throw new EvidenceUnavailable('missing_or_invalid_note');
115
+ if (value.length > BILLING_NOTE_MAX_UNITS)
116
+ throw new EvidenceUnavailable('note_too_large');
117
+ text(value);
118
+ const bytes = Buffer.byteLength(value, 'utf8');
119
+ if (bytes > BILLING_NOTE_MAX_BYTES)
120
+ throw new EvidenceUnavailable('note_too_large');
121
+ const clean = cleanUntrustedText(outerUnwrap(value) ?? value, false);
122
+ const displayed = wrapOrSelf(clean);
123
+ // Compare the displayed content, excluding only the wrapper this server adds.
124
+ const displayCore = outerUnwrap(displayed) ?? displayed;
125
+ return { state: 'complete', display: value, units: value.length, characters: [...value].length, bytes, sha256: sha256(value), displayChanged: displayCore !== value };
126
+ }
127
+ //# sourceMappingURL=billing-review-evidence.js.map
@@ -0,0 +1,12 @@
1
+ import type { ToolContext } from './context/types.js';
2
+ import { type ToolReturn } from './results/envelope.js';
3
+ export declare const BILLING_PAGE_MAX_ROWS = 25;
4
+ export declare const BILLING_RESPONSE_MAX_BYTES = 4194304;
5
+ interface ReadInput {
6
+ operation?: string;
7
+ args: unknown[];
8
+ items?: unknown;
9
+ projection?: string;
10
+ }
11
+ export declare function readBillingReview(ctx: ToolContext, input: ReadInput, signal?: AbortSignal): Promise<ToolReturn>;
12
+ export {};
@@ -0,0 +1,168 @@
1
+ /** Closed Billing Review snapshot; ordinary read/text limits are unchanged. */
2
+ import { InputInvalidError, readOneItem, abortedAnswer } from './dispatch.js';
3
+ import { ok } from './results/envelope.js';
4
+ import { markServerField, sanitiseToolReturn } from './results/untrusted.js';
5
+ import { validScalar } from './time-entry-verification.js';
6
+ import { FILTER_OPS } from './schemas.js';
7
+ import { canonicalRecord, EvidenceUnavailable, noteEvidence, plainRecord, sha256 } from './billing-review-evidence.js';
8
+ export const BILLING_PAGE_MAX_ROWS = 25;
9
+ export const BILLING_RESPONSE_MAX_BYTES = 4_194_304;
10
+ const FIELDS = ['id', 'resourceID', 'ticketID', 'taskID', 'roleID', 'billingCodeID', 'contractID',
11
+ 'startDateTime', 'endDateTime', 'dateWorked', 'hoursWorked', 'hoursToBill', 'offsetHours',
12
+ 'isNonBillable', 'showOnInvoice', 'internalBillingCodeID', 'contractServiceID', 'contractServiceBundleID',
13
+ 'billingApprovalDateTime', 'billingApprovalLevelMostRecent', 'billingApprovalResourceID', 'createDateTime',
14
+ 'creatorUserID', 'impersonatorCreatorResourceID', 'impersonatorUpdaterResourceID', 'lastModifiedDateTime',
15
+ 'lastModifiedUserID', 'timeEntryType', 'isInternalNotesVisibleToComanaged'];
16
+ const REQUIRED_NONNULL = new Set(['id', 'resourceID', 'ticketID', 'dateWorked', 'hoursWorked', 'isNonBillable']);
17
+ const MARKERS = ['partial', 'truncated', 'textCapped', 'noteCharsTruncated', 'scopeNote', 'blindSurface', 'emptyReason', 'relationNote', 'missing', 'errors', 'error'];
18
+ function invalid() { throw new InputInvalidError('Billing Review: invalid identity, scope, input or paging evidence', 'projection'); }
19
+ function own(row, key) {
20
+ const d = Object.getOwnPropertyDescriptor(row, key);
21
+ if (d !== undefined && !('value' in d))
22
+ invalid();
23
+ return d?.value;
24
+ }
25
+ function positive(value) { return Number.isSafeInteger(value) && value > 0; }
26
+ function marked(row) {
27
+ return MARKERS.some(key => { const v = own(row, key); return v !== undefined && v !== false && v !== 0 && v !== null; });
28
+ }
29
+ function validField(key, value) {
30
+ if (value === null)
31
+ return !REQUIRED_NONNULL.has(key);
32
+ if (key === 'id' || key.endsWith('ID'))
33
+ return positive(value);
34
+ if (key === 'isNonBillable' || key === 'showOnInvoice' || key === 'isInternalNotesVisibleToComanaged')
35
+ return typeof value === 'boolean';
36
+ if (key === 'billingApprovalLevelMostRecent' || key === 'timeEntryType')
37
+ return Number.isSafeInteger(value) && value >= 0;
38
+ if (key === 'offsetHours')
39
+ return typeof value === 'number' && Number.isFinite(value);
40
+ if (key === 'hoursWorked' || key === 'hoursToBill')
41
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0;
42
+ return validScalar(key === 'dateWorked' ? key : 'startDateTime', value);
43
+ }
44
+ function entry(value, expectedId) {
45
+ if (!plainRecord(value))
46
+ invalid();
47
+ const id = own(value, 'id');
48
+ const resourceID = own(value, 'resourceID');
49
+ const ticketID = own(value, 'ticketID');
50
+ if (!positive(id) || (expectedId !== undefined && id !== expectedId) || !positive(resourceID) || !positive(ticketID) || own(value, 'taskID') !== null)
51
+ invalid();
52
+ try {
53
+ if (marked(value))
54
+ throw new EvidenceUnavailable('incomplete_source');
55
+ const source = canonicalRecord(value);
56
+ const protectedSource = canonicalRecord(value, true);
57
+ if (FIELDS.some(key => !Object.hasOwn(value, key) || !validField(key, value[key])))
58
+ throw new EvidenceUnavailable('missing_or_invalid_scalar');
59
+ const notes = { summaryNotes: noteEvidence(value.summaryNotes), internalNotes: noteEvidence(value.internalNotes) };
60
+ for (const note of Object.values(notes))
61
+ markServerField(note, 'display', 'document');
62
+ return { state: 'complete', entry: Object.fromEntries(FIELDS.map(key => [key, value[key]])), notes,
63
+ evidence: { canonicalization: 'billing-review-json-v1', sourceSha256: sha256(source), protectedSha256: sha256(protectedSource) } };
64
+ }
65
+ catch (error) {
66
+ if (!(error instanceof EvidenceUnavailable))
67
+ throw error;
68
+ return { state: 'unavailable', id, resourceID, ticketID, reason: error.reason };
69
+ }
70
+ }
71
+ function projectionCondition(condition) {
72
+ if (!plainRecord(condition))
73
+ invalid();
74
+ if (condition.op === 'and' || condition.op === 'or') {
75
+ if (Object.keys(condition).some(key => key !== 'op' && key !== 'items') || !Array.isArray(condition.items))
76
+ invalid();
77
+ return { ...condition, items: condition.items.map(projectionCondition) };
78
+ }
79
+ if (Object.keys(condition).some(key => !['field', 'op', 'value'].includes(key)) || !FIELDS.some(field => field === condition.field) || !FILTER_OPS.some(op => op === condition.op))
80
+ invalid();
81
+ if (!((condition.op === 'eq' && ['id', 'resourceID', 'ticketID', 'taskID'].includes(condition.field)) || (condition.field === 'id' && condition.op === 'gt')))
82
+ return condition;
83
+ let value = condition.value;
84
+ if (value === null && condition.field === 'taskID' && condition.op === 'eq')
85
+ return condition;
86
+ if (typeof value === 'string' && /^[0-9]+$/.test(value.trim()))
87
+ value = Number(value.trim());
88
+ if (!Number.isSafeInteger(value) || value < 0)
89
+ invalid();
90
+ return { ...condition, value };
91
+ }
92
+ function queryBag(input) {
93
+ const bag = input.args[0];
94
+ if (input.args.length !== 1 || !plainRecord(bag) || Object.keys(bag).some(k => k !== 'filter' && k !== 'limit'))
95
+ invalid();
96
+ const limit = bag.limit === undefined ? BILLING_PAGE_MAX_ROWS : bag.limit;
97
+ if (!positive(limit) || limit > BILLING_PAGE_MAX_ROWS || !Array.isArray(bag.filter) || bag.filter.length === 0)
98
+ invalid();
99
+ try {
100
+ if (Buffer.byteLength(canonicalRecord({ filter: bag.filter }), 'utf8') > 8000)
101
+ invalid();
102
+ }
103
+ catch {
104
+ invalid();
105
+ }
106
+ // Canonical fields prevent SDK aliases or input unwrapping from bypassing local identity proof.
107
+ return { filter: [...bag.filter.map(projectionCondition), { field: 'ticketID', op: 'gt', value: 0 }], limit, names: false };
108
+ }
109
+ function queryPage(raw, bag) {
110
+ if (!plainRecord(raw) || Object.keys(raw).some(k => !['items', 'fetched', 'hasMore', 'pagesWalked', ...MARKERS].includes(k)) || marked(raw))
111
+ invalid();
112
+ if (!Array.isArray(raw.items) || raw.items.length > bag.limit || raw.fetched !== raw.items.length || typeof raw.hasMore !== 'boolean' || !positive(raw.pagesWalked) || raw.pagesWalked > 1000 || (raw.items.length === 0 && raw.hasMore))
113
+ invalid();
114
+ let previous = 0;
115
+ for (const condition of bag.filter) {
116
+ if (plainRecord(condition) && condition.field === 'id' && condition.op === 'gt' && Number.isSafeInteger(condition.value) && condition.value >= 0)
117
+ previous = Math.max(previous, condition.value);
118
+ }
119
+ const items = [];
120
+ for (const row of raw.items) {
121
+ const projected = entry(row);
122
+ const identity = (projected.entry ?? projected);
123
+ if (identity.id <= previous)
124
+ invalid();
125
+ previous = identity.id;
126
+ // Re-check top-level conjunctive identities; nested Boolean filtering remains with the SDK/API.
127
+ for (const c of bag.filter) {
128
+ if (plainRecord(c) && c.op === 'eq' && ['id', 'resourceID', 'ticketID', 'taskID'].includes(c.field) && own(row, c.field) !== c.value)
129
+ invalid();
130
+ }
131
+ items.push(projected);
132
+ }
133
+ return { contract: 'billing-review-entry-v1', fresh: true, items,
134
+ paging: { fetched: items.length, hasMore: raw.hasMore, pagesWalked: raw.pagesWalked, nextAfterId: raw.hasMore ? previous : null } };
135
+ }
136
+ export async function readBillingReview(ctx, input, signal) {
137
+ if (input.items !== undefined)
138
+ invalid();
139
+ let project;
140
+ let args;
141
+ if (input.operation === 'time_entries.get') {
142
+ if (input.args.length !== 1 || !positive(input.args[0]))
143
+ invalid();
144
+ const id = input.args[0];
145
+ args = [id];
146
+ project = raw => ({ contract: 'billing-review-entry-v1', fresh: true, items: [entry(raw, id)], paging: { fetched: 1, hasMore: false, pagesWalked: 0, nextAfterId: null } });
147
+ }
148
+ else if (input.operation === 'time_entries.query') {
149
+ const bag = queryBag(input);
150
+ args = [bag];
151
+ project = raw => queryPage(raw, bag);
152
+ }
153
+ else
154
+ invalid();
155
+ // SDK queries are uncached; its fresh option is valid only for primitive get reads.
156
+ const result = await readOneItem(ctx, input.operation, args, signal, input.operation === 'time_entries.get' ? { fresh: true } : undefined, project);
157
+ if (result.aborted)
158
+ return abortedAnswer(ctx.correlationId);
159
+ if (result.scopeNote !== undefined)
160
+ invalid();
161
+ const summary = 'Fresh bounded Billing Review snapshot; display notes are untrusted. Check each entry state.';
162
+ // Measure the actual sanitized ToolReturn, including both structured and mirrored text copies.
163
+ if (Buffer.byteLength(JSON.stringify(sanitiseToolReturn(ok(summary, result.result))), 'utf8') > BILLING_RESPONSE_MAX_BYTES) {
164
+ throw new InputInvalidError('Billing Review response exceeds 4 MiB; retry with a smaller limit', 'args[0].limit');
165
+ }
166
+ return ok(summary, result.result);
167
+ }
168
+ //# sourceMappingURL=billing-review-projection.js.map
@@ -4,6 +4,7 @@ import { invokeDelete, invokeRead, invokeWrite, relationshipMap, resolveAny, sea
4
4
  import { serverCredentialDefaults } from '../../config/load.js';
5
5
  import { normalizeBaseUrl } from '../../base-hosts.js';
6
6
  import { sdkCacheOptions } from '../catalog-data.js';
7
+ import { captureReadRuntime } from '../read-runtime.js';
7
8
  // ---------------------------------------------------------------------------
8
9
  // SDK client construction
9
10
  // ---------------------------------------------------------------------------
@@ -101,6 +102,7 @@ export function buildStdioClient(config, log) {
101
102
  ...(defaults.impersonationResourceId !== undefined ? { impersonationResourceId: defaults.impersonationResourceId } : {}),
102
103
  baseUrl: normalized.baseUrl,
103
104
  });
105
+ captureReadRuntime(client);
104
106
  return { client, origin: normalized.origin };
105
107
  }
106
108
  // ---------------------------------------------------------------------------
@@ -2,6 +2,7 @@ import { credentialShapeProblem } from 'node-autotask';
2
2
  import { serverCredentialDefaults } from '../../config/load.js';
3
3
  import { baseHostAllowed, normalizeBaseUrl } from '../../base-hosts.js';
4
4
  import { CREDENTIAL_LOAD_HINT } from '../../credential.js';
5
+ import { captureReadRuntime } from '../read-runtime.js';
5
6
  import { buildSdkBaseOptions, buildPlaceholderClient } from './client.js';
6
7
  /**
7
8
  * The five origin facts of one request, derived from the header origin and the deployment default. They are kept together on purpose:
@@ -173,6 +174,7 @@ export function createHttpScopeResolver(config, log, pool, baseOptions) {
173
174
  // construction (HostPolicyDeniedError out of the per-request factory).
174
175
  const poolConfig = poolConfigFor(creds, baseNormalized, defaultOrigin, baseOptions);
175
176
  const client = pool.get(poolConfig);
177
+ captureReadRuntime(client);
176
178
  return { client, origin: baseNormalized.origin, poolConfig };
177
179
  },
178
180
  };
@@ -75,4 +75,4 @@ export interface ReadOutcome {
75
75
  * and the untrusted projection of the result. Errors are THROWN — the frame wraps them once, the
76
76
  * `items` form maps them per slot.
77
77
  */
78
- export declare function readOneItem(ctx: ToolContext, operation: string, args: unknown[], signal: AbortSignal | undefined, opts?: InvokeOptions): Promise<ReadOutcome>;
78
+ export declare function readOneItem(ctx: ToolContext, operation: string, args: unknown[], signal: AbortSignal | undefined, opts?: InvokeOptions, projectRaw?: (result: unknown) => unknown): Promise<ReadOutcome>;
@@ -191,7 +191,7 @@ function annotateCatalogRows(result) {
191
191
  * and the untrusted projection of the result. Errors are THROWN — the frame wraps them once, the
192
192
  * `items` form maps them per slot.
193
193
  */
194
- export async function readOneItem(ctx, operation, args, signal, opts) {
194
+ export async function readOneItem(ctx, operation, args, signal, opts, projectRaw) {
195
195
  const rec = ctx.record(operation);
196
196
  if (rec === undefined) {
197
197
  throw new AutotaskConfigError(`invoke: unknown operation "${operation}" — it is not in the capability registry (find the exact key with autotask_catalog)`, { operation });
@@ -252,6 +252,9 @@ export async function readOneItem(ctx, operation, args, signal, opts) {
252
252
  });
253
253
  if (result === undefined)
254
254
  return { aborted: true, result: undefined };
255
+ // Raw evidence must precede deepMarkUntrusted, which replaces excessively nested values.
256
+ if (projectRaw !== undefined)
257
+ return { result: projectRaw(result), ...(scopeNote !== undefined ? { scopeNote } : {}) };
255
258
  if (OWN_STAMP_OPS.has(operation))
256
259
  return { result: markResult(result, ctx.untrustedFields(operation)), ...(scopeNote !== undefined ? { scopeNote } : {}) };
257
260
  // Issue #1: wrap the SDK result's externally-sourced free text — envelope-shaped results are
@@ -1,3 +1,5 @@
1
+ import { readRuntimeProof } from './read-runtime.js';
2
+ import { readBillingReview } from './billing-review-projection.js';
1
3
  import { projectTimeEntryVerification } from './time-entry-verification.js';
2
4
  /**
3
5
  * tools/meta.ts — the discovery and generic-read core:
@@ -25,7 +27,7 @@ import { abortedAnswer, FIELD_CATALOG_MAX_BYTES, InputInvalidError, readOneItem,
25
27
  import { zoneClock } from './clock.js';
26
28
  import { typedErrorPayload } from './results/errors.js';
27
29
  import { markResult, sanitiseVendorOutput } from './results/untrusted.js';
28
- import { ok } from './results/envelope.js';
30
+ import { errorEnvelope, ok } from './results/envelope.js';
29
31
  import { bm25Rank } from './rank.js';
30
32
  import { playbooksFor } from './guide.js';
31
33
  import { FIELD_INFO_EXPENSIVE, fieldLookupCall, udfCatalogCall } from './field-pointer.js';
@@ -601,6 +603,17 @@ export function buildRead(ctx) {
601
603
  if ((args.operation === undefined) === (args.items === undefined)) {
602
604
  throw new InputInvalidError('read: pass exactly one of operation (with args) or items', 'operation');
603
605
  }
606
+ if (args.expectedReadRuntime !== undefined) {
607
+ const proof = readRuntimeProof(ctx.client);
608
+ if (proof.state !== 'available' || proof.sha256 !== args.expectedReadRuntime) {
609
+ return errorEnvelope({ error: true, code: proof.state === 'available' ? 'READ_RUNTIME_MISMATCH' : 'READ_RUNTIME_UNAVAILABLE',
610
+ category: 'policy', retryable: false, notSent: true,
611
+ message: 'Read runtime proof changed or is unavailable; obtain and validate current server.readRuntime before reading.',
612
+ correlationId: ctx.correlationId }, ctx.correlationId);
613
+ }
614
+ }
615
+ if (args.projection === 'billing_review_entry_v1')
616
+ return readBillingReview(ctx, args, signal);
604
617
  if (args.projection !== undefined && args.projection !== 'default') {
605
618
  if (args.operation !== 'time_entries.get' || args.items !== undefined || args.args.length !== 1 || !Number.isSafeInteger(args.args[0]) || args.args[0] <= 0) {
606
619
  throw new InputInvalidError('verification projection requires one time_entries.get and one positive numeric id', 'projection');
@@ -676,7 +689,7 @@ export function buildTenantStatus(ctx) {
676
689
  for (const part of parts) {
677
690
  // Zero wire: this package's version (the same constant as serverInfo and /metadata), kept apart from the vendor `version` part.
678
691
  if (part === 'server') {
679
- data.server = { name: SERVER_NAME, version: SERVER_VERSION, sdkVersion: SDK_VERSION, profile: ctx.config.AUTOTASK_PROFILE };
692
+ data.server = { name: SERVER_NAME, version: SERVER_VERSION, sdkVersion: SDK_VERSION, profile: ctx.config.AUTOTASK_PROFILE, readRuntime: readRuntimeProof(ctx.client) };
680
693
  continue;
681
694
  }
682
695
  // Zero wire: the users' zone (AUTOTASK_USER_TIMEZONE) and its clock (#171), so a client need not guess today's date or zone.
@@ -0,0 +1,18 @@
1
+ import type { ToolClient } from './context/types.js';
2
+ export declare const READ_RUNTIME_CONTRACT = "autotask-read-runtime-v1";
3
+ /** Call synchronously at client construction/resolution, never replace an earlier capture. */
4
+ export declare function captureReadRuntime(client: ToolClient): void;
5
+ /** SDK 0.60 copies these scalars into HttpClient at construction; public config drift cannot re-attest it. */
6
+ export declare function readRuntimeProof(client: ToolClient): {
7
+ state: "unavailable";
8
+ contract: string;
9
+ } | {
10
+ sha256: string;
11
+ contract: string;
12
+ maintenanceMaxWaitMs: number;
13
+ maxRetries: number;
14
+ planHash: string;
15
+ reResolveZoneOn401: boolean;
16
+ sdkVersion: string;
17
+ state: "available";
18
+ };
@@ -0,0 +1,50 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { BUILT_AGAINST_PLAN_HASH, SDK_VERSION } from './catalog-data.js';
3
+ export const READ_RUNTIME_CONTRACT = 'autotask-read-runtime-v1';
4
+ const KEYS = ['maintenanceMaxWaitMs', 'maxRetries', 'reResolveZoneOn401'];
5
+ // Construction facts only, never vendor data or a response cache; pool eviction releases these too.
6
+ const captures = new WeakMap();
7
+ function configOf(client) {
8
+ const value = Object.getOwnPropertyDescriptor(client, 'config')?.value;
9
+ return value !== null && typeof value === 'object' ? value : undefined;
10
+ }
11
+ function boundsOf(config) {
12
+ const maintenanceMaxWaitMs = Object.getOwnPropertyDescriptor(config, 'maintenanceMaxWaitMs')?.value;
13
+ const maxRetries = Object.getOwnPropertyDescriptor(config, 'maxRetries')?.value;
14
+ const reResolveZoneOn401 = Object.getOwnPropertyDescriptor(config, 'reResolveZoneOn401')?.value;
15
+ if (typeof maxRetries !== 'number' || !Number.isSafeInteger(maxRetries) || maxRetries < 0 ||
16
+ typeof maintenanceMaxWaitMs !== 'number' || !Number.isSafeInteger(maintenanceMaxWaitMs) || maintenanceMaxWaitMs < 0 ||
17
+ typeof reResolveZoneOn401 !== 'boolean')
18
+ return undefined;
19
+ return { maintenanceMaxWaitMs, maxRetries, reResolveZoneOn401 };
20
+ }
21
+ /** Call synchronously at client construction/resolution, never replace an earlier capture. */
22
+ export function captureReadRuntime(client) {
23
+ if (captures.has(client))
24
+ return;
25
+ const config = configOf(client);
26
+ const bounds = config === undefined ? undefined : boundsOf(config);
27
+ captures.set(client, config !== undefined && bounds !== undefined ? { config, bounds } : null);
28
+ }
29
+ /** SDK 0.60 copies these scalars into HttpClient at construction; public config drift cannot re-attest it. */
30
+ export function readRuntimeProof(client) {
31
+ const unavailable = { state: 'unavailable', contract: READ_RUNTIME_CONTRACT };
32
+ const capture = captures.get(client);
33
+ const config = configOf(client);
34
+ if (capture == null || config !== capture.config)
35
+ return unavailable;
36
+ const bounds = boundsOf(config);
37
+ if (bounds === undefined || KEYS.some(key => bounds[key] !== capture.bounds[key]))
38
+ return unavailable;
39
+ // Canonical UTF-8 JSON: these exact keys in alphabetical order, no whitespace, no other config.
40
+ const descriptor = {
41
+ contract: READ_RUNTIME_CONTRACT,
42
+ maintenanceMaxWaitMs: bounds.maintenanceMaxWaitMs,
43
+ maxRetries: bounds.maxRetries,
44
+ planHash: BUILT_AGAINST_PLAN_HASH,
45
+ reResolveZoneOn401: bounds.reResolveZoneOn401,
46
+ sdkVersion: SDK_VERSION,
47
+ };
48
+ return { state: 'available', ...descriptor, sha256: createHash('sha256').update(JSON.stringify(descriptor), 'utf8').digest('hex') };
49
+ }
50
+ //# sourceMappingURL=read-runtime.js.map
@@ -64,6 +64,8 @@ const SDK_NEXT = new Set(['supply_input', 'retry', 'stop', 'choose_candidate']);
64
64
  /** The reason code per error code where the code alone decides it (the rest go by category). */
65
65
  const REASON_BY_CODE = {
66
66
  POLICY_DENIED: 'POLICY_DENIED',
67
+ READ_RUNTIME_MISMATCH: 'POLICY_DENIED',
68
+ READ_RUNTIME_UNAVAILABLE: 'POLICY_DENIED',
67
69
  HOST_POLICY_DENIED: 'HOST_POLICY_DENIED',
68
70
  CREDENTIAL_MISSING: 'CREDENTIAL_MISSING',
69
71
  CREDENTIAL_MALFORMED: 'CREDENTIAL_MALFORMED',
@@ -207,7 +207,9 @@ export declare const READ_INPUT: z.ZodPipe<z.ZodObject<{
207
207
  projection: z.ZodPreprocess<z.ZodOptional<z.ZodEnum<{
208
208
  default: "default";
209
209
  time_entry_verification_v1: "time_entry_verification_v1";
210
+ billing_review_entry_v1: "billing_review_entry_v1";
210
211
  }>>, unknown>;
212
+ expectedReadRuntime: z.ZodOptional<z.ZodString>;
211
213
  }, z.core.$strip>, z.ZodTransform<{
212
214
  args: unknown[];
213
215
  operation?: string | undefined;
@@ -215,7 +217,8 @@ export declare const READ_INPUT: z.ZodPipe<z.ZodObject<{
215
217
  operation: string;
216
218
  args: unknown[];
217
219
  }[] | undefined;
218
- projection?: "default" | "time_entry_verification_v1" | undefined;
220
+ projection?: "default" | "time_entry_verification_v1" | "billing_review_entry_v1" | undefined;
221
+ expectedReadRuntime?: string | undefined;
219
222
  }, {
220
223
  args: unknown[];
221
224
  operation?: string | undefined;
@@ -223,7 +226,8 @@ export declare const READ_INPUT: z.ZodPipe<z.ZodObject<{
223
226
  operation: string;
224
227
  args: unknown[];
225
228
  }[] | undefined;
226
- projection?: "default" | "time_entry_verification_v1" | undefined;
229
+ projection?: "default" | "time_entry_verification_v1" | "billing_review_entry_v1" | undefined;
230
+ expectedReadRuntime?: string | undefined;
227
231
  }>>;
228
232
  export declare const RESOLVE_INPUT: z.ZodObject<{
229
233
  identifier: z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>;
@@ -238,8 +238,9 @@ export const READ_INPUT = z.object({
238
238
  operation: unset(OP_KEY.optional()).describe('Exact read key, e.g. tickets.get (autotask_catalog finds it).'),
239
239
  args: unset(ARGS),
240
240
  items: unset(z.array(READ_ITEM).min(1).max(READ_MAX_ITEMS).optional()).describe('Batch reads in one call, each { operation, args }; use instead of operation.'),
241
- projection: unset(z.enum(['default', 'time_entry_verification_v1']).optional()).describe('default keeps the normal read. time_entry_verification_v1 is metadata-only, valid only for one time_entries.get with one numeric id; forced fresh. No note bodies.'),
242
- }).transform(numericQueryBag);
241
+ projection: unset(z.enum(['default', 'time_entry_verification_v1', 'billing_review_entry_v1']).optional()).describe('default: normal read. time_entry_verification_v1: fresh metadata-only get. billing_review_entry_v1: fresh ticket-entry get or bounded query (limit<=25, no includeFields); full bounded display notes and raw hashes.'),
242
+ expectedReadRuntime: z.string().regex(/^[a-f0-9]{64}$/).optional().describe('Require server.readRuntime.sha256 from autotask_tenant_status; changed or unavailable runtime refuses before any vendor dispatch.'),
243
+ }).transform(v => v.projection === 'billing_review_entry_v1' ? v : numericQueryBag(v));
243
244
  export const RESOLVE_INPUT = z.object({
244
245
  identifier: z.union([z.number().int().nonnegative(), z.string().min(1).max(200)]).describe('Numeric id, name, ticket number, serial or email. resources: numeric identifiers are looked up as Resource ids.'),
245
246
  resource: RESOLVE_RESOURCE.optional().describe('Resource to resolve in; omit to sweep several. resources = staff by email, user name or name: active only, API users excluded.'),
@@ -1,2 +1,3 @@
1
1
  export declare const NOTE_VERIFICATION_MAX_BYTES = 1048576;
2
+ export declare function validScalar(key: string, value: unknown): boolean;
2
3
  export declare function projectTimeEntryVerification(result: unknown, entryId: number): Record<string, unknown>;
@@ -16,7 +16,7 @@ function fingerprint(value) {
16
16
  return { state: 'unavailable', reason: 'too_large' };
17
17
  return { state: 'complete', characters: [...value].length, bytes: byteLength, sha256: createHash('sha256').update(value, 'utf8').digest('hex') };
18
18
  }
19
- function validScalar(key, value) {
19
+ export function validScalar(key, value) {
20
20
  if (key === 'id' || key === 'resourceID')
21
21
  return Number.isSafeInteger(value) && value > 0;
22
22
  if (key.endsWith('ID'))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "iit-mcp-autotask",
3
- "version": "0.58.0",
3
+ "version": "0.58.2",
4
4
  "description": "MCP server for the Autotask (Datto) PSA domain, built on the node-autotask SDK",
5
5
  "license": "MIT",
6
6
  "author": "Max Soukhomlinov",
package/server.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "iit-mcp-autotask",
3
- "version": "0.58.0",
3
+ "version": "0.58.2",
4
4
  "description": "MCP server for the Autotask (Datto) PSA API, powered by the node-autotask SDK",
5
5
  "mcpProtocolBaseline": "2026-07-28",
6
6
  "legacyProtocolFallback": "2025-11-25",