iit-mcp-autotask 0.58.0 → 0.58.1

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,75 @@ 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 full bounded note display and protected-field evidence, opt in to `billing_review_entry_v1`:
802
+
803
+ ```json
804
+ {"operation":"time_entries.get","args":[44],"projection":"billing_review_entry_v1"}
805
+ {"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"}
806
+ ```
807
+
808
+ This versioned projection accepts one positive numeric get ID or one query bag containing only a
809
+ nonempty SDK `filter` and optional integer `limit` (default/max 25). Batches, `includeFields`, `walk`,
810
+ `latest`, and note capping are refused. Conditions use only exact, unqualified built-in scalar names
811
+ from the closed `entry` snapshot below, including inside AND/OR groups. Wrappers, prefixes/relation
812
+ fields, case aliases, whitespace, unsafe characters, note fields and UDF conditions are refused before
813
+ vendor work. Operators must also use their exact canonical SDK spelling, without wrappers.
814
+ Resolve company scope to ticket IDs separately, then filter by `ticketID`/`resourceID`.
815
+ Generic reads retain the full SDK filter grammar. The projection adds `ticketID gt 0` and refuses
816
+ non-ticket/task rows. No initial date cutoff is added.
817
+
818
+ The closed result is `{contract:"billing-review-entry-v1", fresh:true, items, paging}`. Each item is
819
+ `{state:"complete", entry, notes, evidence}` or `{state:"unavailable", id, resourceID, ticketID, reason}`.
820
+ The closed `entry` includes every SDK time-entry scalar except note bodies: all four editable fields
821
+ are represented by `billingCodeID`, `contractID`, and the two `notes` records. Reference, role, time,
822
+ hours/offset, invoice/nonbillable, internal billing, service/bundle, approval, creator/updater and
823
+ modified fields must all be present with valid types (nullable nonessential fields are accepted).
824
+ Explicit NULL `startDateTime`/`endDateTime` values are retained for hours-only ticket entries, as allowed
825
+ by the [vendor TimeEntries contract](https://webservices.autotask.net/help/developerhelp/Content/APIs/REST/Entities/TimeEntriesEntity.htm).
826
+ Both keys must still be present; `dateWorked` and finite `hoursWorked` remain required. NULL clock
827
+ fields remain protected by the digests, and callers cannot infer an overlap interval when absent.
828
+ Missing/invalid fields cannot produce complete evidence. Unknown returned fields are hashed but never
829
+ returned. Invalid identities, scope or paging fail the whole call, without echoing the source record.
830
+
831
+ String notes carry `{state:"complete", display, units, characters, bytes, sha256, displayChanged}`;
832
+ NULL carries `{state:"null", display:null}`. Lengths and SHA256 describe exact raw UTF-8 before cleaning:
833
+ UTF-16 units, Unicode code points and UTF-8 bytes respectively. Lone surrogates are refused.
834
+ `display` remains untrusted: unsafe controls are stripped and wrapper forgeries normalized, with full
835
+ bounded prose instead of the normal 500-character cap. `displayChanged` compares raw text with the
836
+ displayed content excluding the server's wrapper; it includes literal-wrapper neutralization and
837
+ stripping. Display text is never evidence of original bytes. Callers should refuse deterministic note
838
+ edits when normalization prevents preserving the original. An unsupported/oversized note makes only
839
+ that entry unavailable; the row and its position remain in the page.
840
+
841
+ `evidence` contains `canonicalization:"billing-review-json-v1"`, `sourceSha256` and `protectedSha256`.
842
+ The source is the entire raw API record, including unknown fields, rather than wire JSON bytes.
843
+ Canonicalization sorts object keys by UTF-16 order, uses JavaScript JSON string/finite-number encoding,
844
+ preserves array order, and rejects unsupported values, accessors, non-plain objects and invalid Unicode.
845
+ Protected evidence excludes **only** `summaryNotes`, `internalNotes`, `billingCodeID`, `contractID` and
846
+ `lastModifiedDateTime`; all other audit/financial/time/reference and unknown fields remain protected.
847
+ Compare these digests as opaque strings; do not recreate JavaScript numeric encoding in another language.
848
+
849
+ Bounds: each note is at most 32,000 UTF-16 units / 96,000 UTF-8 bytes; each canonical record is at most
850
+ 1,048,576 encoded bytes, depth 16 (root depth 0), and 4,096 visited values/own keys per container.
851
+ Each query filter is at most 8,000 canonical UTF-8 bytes. The complete sanitized tool result, including
852
+ its structured data and mirrored text, must fit 4,194,304 UTF-8 bytes; retry the same cursor with a smaller
853
+ limit if it does not. No row is silently removed to fit a cap.
854
+
855
+ `paging` contains `fetched`, `hasMore`, `pagesWalked`, and `nextAfterId` (the last ID when more remain,
856
+ otherwise NULL). Returned IDs must be strictly increasing, above the supplied top-level `id gt`
857
+ bound, with matching counts and no partial/capped/scope markers. Resume by retaining the same scope
858
+ filter and adding/updating a top-level `id gt nextAfterId` condition. `hasMore:false` describes this
859
+ query's current transport exhaustion; callers still check every entry's state and their billing rules.
860
+ Validation covers only the exposed SDK `BoundedQueryResult`. SDK 0.60 discards unknown outer vendor
861
+ response-envelope metadata; this projection cannot inspect discarded metadata or establish tenant-wide
862
+ completeness. Top-level identity equality and `id gt` conditions accept safe non-negative integer
863
+ numbers or decimal digit strings (surrounding whitespace is ignored); returned row IDs remain strictly
864
+ numeric. Identity values normalize recursively, including inside groups. Local row-level identity
865
+ re-checks cover top-level conjunctive predicates; the SDK/API enforces nested Boolean filtering.
866
+ Bounds inside OR groups are not applied globally.
867
+ GET uses the SDK forced-fresh option; queries execute live because the SDK query path is uncached
868
+ (the get-only fresh option is omitted). Server-owned `names:false` avoids derived label expansion.
869
+ A call may still need SDK metadata/relation requests or multiple vendor pages; the 25-row bound
870
+ is a returned-row cap, not a promise of one vendor request. No projection adds a server read cache or
871
+ 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
@@ -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,4 @@
1
+ import { readBillingReview } from './billing-review-projection.js';
1
2
  import { projectTimeEntryVerification } from './time-entry-verification.js';
2
3
  /**
3
4
  * tools/meta.ts — the discovery and generic-read core:
@@ -601,6 +602,8 @@ export function buildRead(ctx) {
601
602
  if ((args.operation === undefined) === (args.items === undefined)) {
602
603
  throw new InputInvalidError('read: pass exactly one of operation (with args) or items', 'operation');
603
604
  }
605
+ if (args.projection === 'billing_review_entry_v1')
606
+ return readBillingReview(ctx, args, signal);
604
607
  if (args.projection !== undefined && args.projection !== 'default') {
605
608
  if (args.operation !== 'time_entries.get' || args.items !== undefined || args.args.length !== 1 || !Number.isSafeInteger(args.args[0]) || args.args[0] <= 0) {
606
609
  throw new InputInvalidError('verification projection requires one time_entries.get and one positive numeric id', 'projection');
@@ -207,6 +207,7 @@ 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>;
211
212
  }, z.core.$strip>, z.ZodTransform<{
212
213
  args: unknown[];
@@ -215,7 +216,7 @@ export declare const READ_INPUT: z.ZodPipe<z.ZodObject<{
215
216
  operation: string;
216
217
  args: unknown[];
217
218
  }[] | undefined;
218
- projection?: "default" | "time_entry_verification_v1" | undefined;
219
+ projection?: "default" | "time_entry_verification_v1" | "billing_review_entry_v1" | undefined;
219
220
  }, {
220
221
  args: unknown[];
221
222
  operation?: string | undefined;
@@ -223,7 +224,7 @@ export declare const READ_INPUT: z.ZodPipe<z.ZodObject<{
223
224
  operation: string;
224
225
  args: unknown[];
225
226
  }[] | undefined;
226
- projection?: "default" | "time_entry_verification_v1" | undefined;
227
+ projection?: "default" | "time_entry_verification_v1" | "billing_review_entry_v1" | undefined;
227
228
  }>>;
228
229
  export declare const RESOLVE_INPUT: z.ZodObject<{
229
230
  identifier: z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>;
@@ -238,8 +238,8 @@ 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
+ }).transform(v => v.projection === 'billing_review_entry_v1' ? v : numericQueryBag(v));
243
243
  export const RESOLVE_INPUT = z.object({
244
244
  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
245
  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.1",
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.1",
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",