iit-mcp-autotask 0.54.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.
Files changed (164) hide show
  1. package/.env.example +123 -0
  2. package/LICENSE +21 -0
  3. package/README.md +788 -0
  4. package/capabilities.json +487 -0
  5. package/dist/access/gate.d.ts +34 -0
  6. package/dist/access/gate.js +76 -0
  7. package/dist/access/grants.d.ts +20 -0
  8. package/dist/access/grants.js +35 -0
  9. package/dist/access/write-env.d.ts +41 -0
  10. package/dist/access/write-env.js +166 -0
  11. package/dist/auth.d.ts +74 -0
  12. package/dist/auth.js +129 -0
  13. package/dist/base-hosts.d.ts +38 -0
  14. package/dist/base-hosts.js +70 -0
  15. package/dist/config/load.d.ts +28 -0
  16. package/dist/config/load.js +105 -0
  17. package/dist/config/schema.d.ts +166 -0
  18. package/dist/config/schema.js +311 -0
  19. package/dist/credential.d.ts +28 -0
  20. package/dist/credential.js +32 -0
  21. package/dist/doctor.d.ts +112 -0
  22. package/dist/doctor.js +154 -0
  23. package/dist/http-guard.d.ts +57 -0
  24. package/dist/http-guard.js +134 -0
  25. package/dist/http.d.ts +50 -0
  26. package/dist/http.js +290 -0
  27. package/dist/lifecycle.d.ts +29 -0
  28. package/dist/lifecycle.js +52 -0
  29. package/dist/logger.d.ts +26 -0
  30. package/dist/logger.js +28 -0
  31. package/dist/main.d.ts +12 -0
  32. package/dist/main.js +283 -0
  33. package/dist/policy.d.ts +54 -0
  34. package/dist/policy.js +80 -0
  35. package/dist/tools/aggregate.d.ts +16 -0
  36. package/dist/tools/aggregate.js +64 -0
  37. package/dist/tools/capabilities-manifest.d.ts +4 -0
  38. package/dist/tools/capabilities-manifest.js +94 -0
  39. package/dist/tools/catalog-data.d.ts +116 -0
  40. package/dist/tools/catalog-data.js +207 -0
  41. package/dist/tools/clock.d.ts +17 -0
  42. package/dist/tools/clock.js +43 -0
  43. package/dist/tools/composites.d.ts +36 -0
  44. package/dist/tools/composites.js +305 -0
  45. package/dist/tools/context/client.d.ts +41 -0
  46. package/dist/tools/context/client.js +139 -0
  47. package/dist/tools/context/derive.d.ts +9 -0
  48. package/dist/tools/context/derive.js +32 -0
  49. package/dist/tools/context/scope.d.ts +24 -0
  50. package/dist/tools/context/scope.js +180 -0
  51. package/dist/tools/context/types.d.ts +141 -0
  52. package/dist/tools/context/types.js +2 -0
  53. package/dist/tools/dispatch.d.ts +78 -0
  54. package/dist/tools/dispatch.js +272 -0
  55. package/dist/tools/field-pointer.d.ts +25 -0
  56. package/dist/tools/field-pointer.js +45 -0
  57. package/dist/tools/guide.d.ts +30 -0
  58. package/dist/tools/guide.js +97 -0
  59. package/dist/tools/lists.d.ts +9 -0
  60. package/dist/tools/lists.js +205 -0
  61. package/dist/tools/meta.d.ts +22 -0
  62. package/dist/tools/meta.js +709 -0
  63. package/dist/tools/output-file.d.ts +26 -0
  64. package/dist/tools/output-file.js +140 -0
  65. package/dist/tools/rank.d.ts +21 -0
  66. package/dist/tools/rank.js +57 -0
  67. package/dist/tools/reasons.d.ts +33 -0
  68. package/dist/tools/reasons.js +121 -0
  69. package/dist/tools/register.d.ts +23 -0
  70. package/dist/tools/register.js +50 -0
  71. package/dist/tools/resolves.d.ts +28 -0
  72. package/dist/tools/resolves.js +399 -0
  73. package/dist/tools/results/envelope.d.ts +55 -0
  74. package/dist/tools/results/envelope.js +63 -0
  75. package/dist/tools/results/errors.d.ts +147 -0
  76. package/dist/tools/results/errors.js +384 -0
  77. package/dist/tools/results/untrusted.d.ts +129 -0
  78. package/dist/tools/results/untrusted.js +218 -0
  79. package/dist/tools/revenue-rollup.d.ts +8 -0
  80. package/dist/tools/revenue-rollup.js +112 -0
  81. package/dist/tools/schemas.d.ts +467 -0
  82. package/dist/tools/schemas.js +444 -0
  83. package/dist/tools/scope-guard.d.ts +2 -0
  84. package/dist/tools/scope-guard.js +11 -0
  85. package/dist/tools/server-version.d.ts +3 -0
  86. package/dist/tools/server-version.js +14 -0
  87. package/dist/tools/server.d.ts +92 -0
  88. package/dist/tools/server.js +170 -0
  89. package/dist/tools/surface.d.ts +37 -0
  90. package/dist/tools/surface.js +94 -0
  91. package/dist/tools/tsv.d.ts +52 -0
  92. package/dist/tools/tsv.js +95 -0
  93. package/dist/tools/write/apply.d.ts +40 -0
  94. package/dist/tools/write/apply.js +500 -0
  95. package/dist/tools/write/checks.d.ts +39 -0
  96. package/dist/tools/write/checks.js +137 -0
  97. package/dist/tools/write/common.d.ts +23 -0
  98. package/dist/tools/write/common.js +33 -0
  99. package/dist/tools/write/facts.d.ts +52 -0
  100. package/dist/tools/write/facts.js +151 -0
  101. package/dist/tools/write/outcome.d.ts +23 -0
  102. package/dist/tools/write/outcome.js +67 -0
  103. package/dist/tools/write/parse.d.ts +37 -0
  104. package/dist/tools/write/parse.js +166 -0
  105. package/dist/tools/write/payload.d.ts +44 -0
  106. package/dist/tools/write/payload.js +119 -0
  107. package/dist/tools/write/preview.d.ts +3 -0
  108. package/dist/tools/write/preview.js +317 -0
  109. package/dist/tools/write/snapshot.d.ts +68 -0
  110. package/dist/tools/write/snapshot.js +360 -0
  111. package/dist/tools/write-guidance.d.ts +174 -0
  112. package/dist/tools/write-guidance.js +317 -0
  113. package/dist/tools/write.d.ts +9 -0
  114. package/dist/tools/write.js +10 -0
  115. package/dist/write/canonical.d.ts +12 -0
  116. package/dist/write/canonical.js +31 -0
  117. package/dist/write/evaluate.d.ts +77 -0
  118. package/dist/write/evaluate.js +91 -0
  119. package/dist/write/hard-rules.d.ts +49 -0
  120. package/dist/write/hard-rules.js +48 -0
  121. package/dist/write/runtime.d.ts +37 -0
  122. package/dist/write/runtime.js +72 -0
  123. package/dist/write/store/audit-log.d.ts +13 -0
  124. package/dist/write/store/audit-log.js +25 -0
  125. package/dist/write/store/constants.d.ts +34 -0
  126. package/dist/write/store/constants.js +35 -0
  127. package/dist/write/store/files.d.ts +44 -0
  128. package/dist/write/store/files.js +157 -0
  129. package/dist/write/store/heartbeat.d.ts +9 -0
  130. package/dist/write/store/heartbeat.js +65 -0
  131. package/dist/write/store/ledger.d.ts +15 -0
  132. package/dist/write/store/ledger.js +86 -0
  133. package/dist/write/store/lifecycle.d.ts +35 -0
  134. package/dist/write/store/lifecycle.js +114 -0
  135. package/dist/write/store/lock.d.ts +97 -0
  136. package/dist/write/store/lock.js +464 -0
  137. package/dist/write/store/op-lock.d.ts +13 -0
  138. package/dist/write/store/op-lock.js +175 -0
  139. package/dist/write/store/plan-store.d.ts +7 -0
  140. package/dist/write/store/plan-store.js +48 -0
  141. package/dist/write/store/plans.d.ts +5 -0
  142. package/dist/write/store/plans.js +19 -0
  143. package/dist/write/store/types.d.ts +195 -0
  144. package/dist/write/store/types.js +2 -0
  145. package/dist/write/store.d.ts +6 -0
  146. package/dist/write/store.js +182 -0
  147. package/examples/agentgateway.write-gate.yaml +29 -0
  148. package/package.json +71 -0
  149. package/server.json +69 -0
  150. package/skills/ar-aging.md +65 -0
  151. package/skills/company-360.md +69 -0
  152. package/skills/contract-profitability.md +65 -0
  153. package/skills/crm-management.md +87 -0
  154. package/skills/filter-semantics.md +75 -0
  155. package/skills/invoice-export.md +61 -0
  156. package/skills/log-time-entry.md +77 -0
  157. package/skills/non-chargeable-work.md +67 -0
  158. package/skills/portfolio-margin.md +66 -0
  159. package/skills/recurring-revenue.md +65 -0
  160. package/skills/revenue-rollup.md +65 -0
  161. package/skills/slim-reads.md +67 -0
  162. package/skills/ticket-triage.md +64 -0
  163. package/skills/unbilled-work-review.md +66 -0
  164. package/skills/wip-hours.md +68 -0
@@ -0,0 +1,48 @@
1
+ /** AES-256-GCM plans and expiry pruning; shared-directory locks live in the state store. */
2
+ import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readdirSync, readFileSync, statSync, unlinkSync, writeSync } from 'node:fs';
3
+ import { createCipheriv, randomBytes } from 'node:crypto';
4
+ import { join } from 'node:path';
5
+ import { UNREADABLE_PLAN_MAX_AGE_MS } from './constants.js';
6
+ import { decryptPlan, planKeyFrom } from './plans.js';
7
+ export function createPlanStore({ dir, key, now }) {
8
+ const planKey = planKeyFrom(key);
9
+ const plansDir = join(dir, 'plans');
10
+ mkdirSync(plansDir, { recursive: true, mode: 0o700 });
11
+ /** The decrypted plan in `plansDir/<h>`, or undefined when absent or not authentic (forged, edited, swapped). */
12
+ const readPlan = (h) => {
13
+ if (!/^pln_[a-z2-7]{26}$/.test(h))
14
+ return undefined;
15
+ const p = join(plansDir, h);
16
+ if (!existsSync(p))
17
+ return undefined;
18
+ try {
19
+ return decryptPlan(planKey, h, readFileSync(p, 'utf8'));
20
+ }
21
+ catch {
22
+ return undefined;
23
+ }
24
+ };
25
+ // Expired plans go at boot, by the plan's OWN expiry (every peer boot runs this prune). A file that cannot
26
+ // be decrypted (another key, corrupt) falls back to its age.
27
+ for (const name of readdirSync(plansDir)) {
28
+ const p = join(plansDir, name);
29
+ const plan = readPlan(name);
30
+ if (plan !== undefined ? now() > plan.expiresAt : now() - statSync(p).mtimeMs > UNREADABLE_PLAN_MAX_AGE_MS)
31
+ unlinkSync(p);
32
+ }
33
+ const store = {
34
+ savePlan(plan) {
35
+ const iv = randomBytes(12);
36
+ const cipher = createCipheriv('aes-256-gcm', planKey, iv);
37
+ cipher.setAAD(Buffer.from(plan.handle));
38
+ const ct = Buffer.concat([cipher.update(JSON.stringify(plan), 'utf8'), cipher.final()]);
39
+ const fd = openSync(join(plansDir, plan.handle), 'wx', 0o600);
40
+ writeSync(fd, Buffer.concat([iv, cipher.getAuthTag(), ct]).toString('base64'));
41
+ fsyncSync(fd);
42
+ closeSync(fd);
43
+ },
44
+ loadPlan: readPlan,
45
+ };
46
+ return store;
47
+ }
48
+ //# sourceMappingURL=plan-store.js.map
@@ -0,0 +1,5 @@
1
+ import type { PlanRecord } from './types.js';
2
+ /** The plan-encryption key HKDF-derived from `state.key`. */
3
+ export declare const planKeyFrom: (stateKey: Buffer) => Buffer;
4
+ /** A plan file's text decrypted and authenticated (the handle is the AAD), or undefined when forged, edited or swapped. */
5
+ export declare function decryptPlan(planKey: Buffer, handle: string, fileText: string): PlanRecord | undefined;
@@ -0,0 +1,19 @@
1
+ /** Plan encryption key derivation and AES-256-GCM plan decryption (issue #88). */
2
+ import { createDecipheriv, hkdfSync } from 'node:crypto';
3
+ /** The plan-encryption key HKDF-derived from `state.key`. */
4
+ export const planKeyFrom = (stateKey) => Buffer.from(hkdfSync('sha256', stateKey, Buffer.alloc(0), 'iit-mcp-autotask plan encryption', 32));
5
+ /** A plan file's text decrypted and authenticated (the handle is the AAD), or undefined when forged, edited or swapped. */
6
+ export function decryptPlan(planKey, handle, fileText) {
7
+ try {
8
+ const raw = Buffer.from(fileText, 'base64');
9
+ const decipher = createDecipheriv('aes-256-gcm', planKey, raw.subarray(0, 12));
10
+ decipher.setAAD(Buffer.from(handle));
11
+ decipher.setAuthTag(raw.subarray(12, 28));
12
+ const plan = JSON.parse(Buffer.concat([decipher.update(raw.subarray(28)), decipher.final()]).toString('utf8'));
13
+ return plan.handle === handle ? plan : undefined;
14
+ }
15
+ catch {
16
+ return undefined;
17
+ }
18
+ }
19
+ //# sourceMappingURL=plans.js.map
@@ -0,0 +1,195 @@
1
+ /** The state store contract: plan, ledger and audit records and the `StateStore` interface (issue #88). */
2
+ import type { Logger } from '../../logger.js';
3
+ import type { Counters, WriteFacts } from '../evaluate.js';
4
+ /** What a plan names as its target: the resource and the ids a snapshot read. */
5
+ export interface PlanTargets {
6
+ resource: string;
7
+ parentId?: number;
8
+ id?: number;
9
+ /** A move (issue #107): the target ticket; `id` is the source record. */
10
+ toId?: number;
11
+ }
12
+ /** The stored plan (encrypted at rest). */
13
+ export interface PlanRecord {
14
+ handle: string;
15
+ planHash: string;
16
+ principal: string;
17
+ tenantId: string;
18
+ op: string;
19
+ args: unknown[];
20
+ targets: PlanTargets;
21
+ policyHash: string;
22
+ /** `allow`: executable now. `gate`: executes only once a person confirms it at apply. */
23
+ decision: 'allow' | 'gate';
24
+ facts: WriteFacts;
25
+ reason?: string;
26
+ /** #301: the SDK's `describeWrite` rendering at preview: `summary` (its headline) is the echo apply checks. */
27
+ summary: string;
28
+ lines: string[];
29
+ reversible: boolean;
30
+ createdAt: number;
31
+ expiresAt: number;
32
+ }
33
+ export type LedgerState = 'sending' | 'succeeded' | 'failed' | 'unknown';
34
+ /** The recorded outcome a replay answers with (no vendor data: ids and codes only). */
35
+ export interface LedgerOutcome {
36
+ code?: string;
37
+ httpStatus?: number;
38
+ retryable?: boolean;
39
+ id?: number | string;
40
+ /** A move (issue #107): the source record and the new one (ids only; MOVE_PARTIAL names both). */
41
+ sourceId?: number;
42
+ newId?: number;
43
+ /** FIELD_NOT_PERSISTED (issue #103): the field names the vendor did not apply (names only, never values). */
44
+ fields?: string[];
45
+ }
46
+ export interface LedgerEntry {
47
+ idemKey: string;
48
+ planHash: string;
49
+ targetKey: string;
50
+ op: string;
51
+ state: LedgerState;
52
+ at: number;
53
+ outcome?: LedgerOutcome;
54
+ /** A succeeded create: the new record, who created it on which tenant, and its companies then. */
55
+ created?: {
56
+ resource: string;
57
+ id: number | string;
58
+ companyIds: number[];
59
+ principal: string;
60
+ tenantId: string;
61
+ };
62
+ /** The per-boot identity of the process that appended this line (issue #68); absent on legacy entries. */
63
+ boot?: string;
64
+ /** The pid of the process that appended this line (issue #68); absent on legacy entries. */
65
+ pid?: number;
66
+ /** How the human confirmed this write (`elicitation`); absent when no confirmation was needed. */
67
+ approverId?: string;
68
+ }
69
+ /** The identity fields of a credential (never its secret): what the tenant id is an HMAC of. */
70
+ export interface TenantIdentity {
71
+ integrationCode: string;
72
+ username: string;
73
+ origin: string;
74
+ impersonationId?: string;
75
+ }
76
+ export interface AuditEvent {
77
+ event: 'preview' | 'apply_start' | 'apply_result' | 'apply_refused' | 'lock_takeover' | 'gate_confirmed' | 'gate_refused';
78
+ principal: string;
79
+ op: string;
80
+ targets?: PlanTargets;
81
+ planHash?: string;
82
+ decision: string;
83
+ reasons: string[];
84
+ reason?: string;
85
+ /** The rule that decided (the submitter pin: `expense_report_submitter_pin`) with the pinned create's submitter and week. */
86
+ rule?: string;
87
+ submitterID?: string;
88
+ weekEnding?: string;
89
+ /** How the human confirmed the write (`elicitation`). */
90
+ approverId?: string;
91
+ /** `lock_takeover` only: the pid the lock named before this process took it over. */
92
+ deadPid?: number;
93
+ /** `lock_takeover` only: the per-boot identity the lock named (absent for pre-V5 locks). */
94
+ deadBoot?: string;
95
+ }
96
+ /** The facts /ready reports on the state lock (issue #55): age, holder id, lease freshness. */
97
+ export interface LockInfo {
98
+ /** This process is the primary (holds the lock). */
99
+ held: boolean;
100
+ /** The holder the lock currently names (absent when the lock is gone or unreadable). */
101
+ holder?: {
102
+ pid: number;
103
+ boot?: string;
104
+ host?: string;
105
+ };
106
+ /** ms since the holder's `startedAt` (absent when the lock names no parseable start time). */
107
+ ageMs?: number;
108
+ /** ms since the holder's last lease refresh (absent when no readable lease: a pre-lease 0.6.0 holder). */
109
+ leaseAgeMs?: number;
110
+ /** True when a readable lease is older than {@link LEASE_EXPIRY_MS}. */
111
+ leaseExpired?: boolean;
112
+ /** How many processes have registered in `<state>/holders/` (including this one, issue #68). No liveness filter: dead registrations are swept at the next boot. */
113
+ holders: number;
114
+ }
115
+ /** Why an op-lock acquisition gave up: the bounded wait ran out, or the op lock needs an operator. */
116
+ export type OpLockBlocked = {
117
+ code: 'STATE_UNAVAILABLE';
118
+ next: 'retry';
119
+ detail: string;
120
+ };
121
+ export interface StateStore {
122
+ readonly dir: string;
123
+ tenantId(identity: TenantIdentity): string;
124
+ newHandle(): string;
125
+ savePlan(plan: PlanRecord): void;
126
+ /** The decrypted plan, or undefined when absent or not authentic (forged, edited, swapped). */
127
+ loadPlan(handle: string): PlanRecord | undefined;
128
+ /** The latest ledger entry for an idempotency key (a fresh scan of the file). */
129
+ lookup(idemKey: string): LedgerEntry | undefined;
130
+ /** Append + fsync (one O_APPEND line; the line is stamped with this boot's identity). */
131
+ append(entry: LedgerEntry): void;
132
+ counters(op: string, now: number): Counters;
133
+ /** True while an unknown outcome on this target is younger than the cooldown. */
134
+ coolingDown(targetKey: string, now: number): boolean;
135
+ /** Append one audit event under the shared op lock. */
136
+ audit(event: AuditEvent, now: number): void;
137
+ /** The facts /ready reports on the state lock: who holds it, how long, and how fresh its lease is. */
138
+ lockInfo(): LockInfo;
139
+ killed(): boolean;
140
+ /**
141
+ * Why writes may not run right now: the kill switch (stop), this process's holder registration
142
+ * gone (stop) or unreadable for the moment (retry); undefined when writes may run.
143
+ */
144
+ blocked(): {
145
+ code: 'KILL_SWITCH' | 'STATE_UNAVAILABLE';
146
+ next: 'stop' | 'retry';
147
+ detail: string;
148
+ } | undefined;
149
+ /**
150
+ * Take the per-operation lock (issue #68). Returns undefined when acquired — the caller must
151
+ * then call {@link releaseOpLock} — or the reason the bounded wait gave up.
152
+ */
153
+ acquireOpLock(): OpLockBlocked | undefined;
154
+ /** Release the per-operation lock if it is still this process's. */
155
+ releaseOpLock(): void;
156
+ /** One apply at a time per process. */
157
+ withApplyLock<T>(fn: () => Promise<T>): Promise<T>;
158
+ close(): void;
159
+ }
160
+ /**
161
+ * Take the state lock: O_EXCL, or a takeover of a holder that is no longer active, or — when the
162
+ * current holder is a LIVE primary — a plain secondary boot (issue #68): the lock stays with the
163
+ * primary and this process shares the dir under the op lock.
164
+ *
165
+ * The takeover is serialised by a second O_EXCL file, `lock.takeover` (review F7): only its holder
166
+ * may replace the stale lock, and it re-reads the lock first, so two processes booting after a crash
167
+ * cannot both take over (the loser sees either the takeover file — and now WAITS for the taker
168
+ * instead of refusing — or the winner's live pid + fresh lease). A takeover file that survives the
169
+ * wait cap (a crash mid-takeover left it behind) refuses boot until an operator removes it.
170
+ *
171
+ * The verdict has three parts (issue #55): another host's lock is never taken (R6); a FRESH lease
172
+ * (the holder rewrote `lock.lease` within {@link LEASE_EXPIRY_MS}) vetoes the takeover outright —
173
+ * a live holder is never taken, and a fresh lease is stronger liveness evidence than the pid
174
+ * probe; otherwise the holder is dead if its pid answers ESRCH (`dead_pid`), or — with an expired
175
+ * lease — if a RECYCLED pid answers at the old holder's number after a container replacement
176
+ * (`lease_expired`).
177
+ */
178
+ export interface LockTakeover {
179
+ /** The pid the lock named before this process took it over. */
180
+ deadPid: number;
181
+ /** The per-boot identity the lock named (absent for pre-V5 locks). */
182
+ deadBoot?: string;
183
+ /** Why the holder was judged not active. */
184
+ reason: 'dead_pid' | 'lease_expired';
185
+ }
186
+ export interface OpenStoreOptions {
187
+ log: Logger;
188
+ /** `AUTOTASK_KILL_FILE`; default `<state>/KILL`. */
189
+ killFile?: string;
190
+ /** Called when the kill file is seen or changes (issue #311): the runtime ends its session grants. */
191
+ onKill?: () => void;
192
+ now?: () => number;
193
+ /** The op lock's wait cap (and the lock-takeover contention wait). Default {@link OP_LOCK_WAIT_MS}. */
194
+ opLockWaitMs?: number;
195
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1,6 @@
1
+ import type { StateStore, OpenStoreOptions } from './store/types.js';
2
+ export { PLAN_TTL_MS, LEDGER_RETENTION_MS, COOLDOWN_MS, COOLDOWN_MINUTES, LEASE_REFRESH_MS, LEASE_EXPIRY_MS, OP_LOCK_POLL_MS, OP_LOCK_WAIT_MS } from './store/constants.js';
3
+ export type { PlanTargets, PlanRecord, LedgerState, LedgerOutcome, LedgerEntry, TenantIdentity, AuditEvent, LockInfo, OpLockBlocked, StateStore, LockTakeover, OpenStoreOptions } from './store/types.js';
4
+ export { planKeyFrom, decryptPlan } from './store/plans.js';
5
+ /** Open (or create) the state directory; throws ConfigError on every boot refusal. */
6
+ export declare function openStateStore(dir: string, opts: OpenStoreOptions): StateStore;
@@ -0,0 +1,182 @@
1
+ /**
2
+ * write/store.ts — the operator profile's state directory (B2): many processes per dir (issue #68).
3
+ *
4
+ * `<state>/` (0700) holds:
5
+ * - `lock`: the PRIMARY holder record ({pid, boot, host, startedAt}), created with O_EXCL at boot
6
+ * (a racing boot that reads the winner's half-written body waits it out, not refuses).
7
+ * A boot that finds a LIVE primary (same host, a FRESH lease) no longer refuses: it boots as a
8
+ * SECONDARY (issue #68) — many processes share the dir, and the op lock (below) serialises
9
+ * their writes. Primary succession keeps the #55 machinery unchanged: a dead pid is taken over
10
+ * (`dead_pid`), a RECYCLED pid with an EXPIRED lease is taken over (`lease_expired`, the
11
+ * container-replacement case where the new container's pid space reuses the old holder's number),
12
+ * another host's lock is never taken (R6), the takeover is serialised by `lock.takeover`
13
+ * (F7, with the R13 re-check) and audit-logged as a `lock_takeover` line. Limits and counters
14
+ * are therefore per state dir.
15
+ * ponytail: single host only; a DB-backed ledger is the upgrade if several hosts must share one.
16
+ * - `lock.lease` (0600, {pid, boot, host, at}): the primary's heartbeat, atomically rewritten every
17
+ * LEASE_REFRESH_MS (5 s) while it is primary. A fresh lease (no older than 3 refresh cycles,
18
+ * LEASE_EXPIRY_MS = 15 s) vetoes any takeover — a live primary is never taken, and a fresh
19
+ * lease is stronger liveness evidence than the pid probe. A primary that loses the lock at
20
+ * runtime stops refreshing it.
21
+ * - `holders/<boot>` (0600, {pid, boot, host, startedAt}) and `holders/<boot>.lease` (0600,
22
+ * {pid, boot, host, at}): the holder registry (issue #68). EVERY process — primary and
23
+ * secondary — registers its boot here BEFORE any other state work and refreshes the lease with
24
+ * the same heartbeat; close() removes its own pair. A boot sweeps the registry of dead peers
25
+ * (the lock's liveness verdict) before it rewrites the ledger, so a `sending` entry becomes
26
+ * `unknown` only when its origin is NOT a live holder (a live peer's in-flight write stays
27
+ * `sending`). A process whose own registration file goes missing stops new writes
28
+ * (`STATE_UNAVAILABLE`): the registration replaced "lost the lock" as the runtime stop signal.
29
+ * - `op.lock` (+ `op.lock.lease`, `op.lock.takeover`): the per-operation lock (issue #68) — the
30
+ * short critical sections every process takes to write shared state: the boot ledger rewrite,
31
+ * the apply claim (lookup + the `sending` append), the apply's result append (a peer that
32
+ * boots between our open('a') and writeSync renames the ledger out from under the write and
33
+ * orphans the line — the result and its audit line ride ONE acquisition) and every audit
34
+ * append. Same mechanics as the primary lock (O_EXCL, the F7 takeover serialisation with the
35
+ * R13 re-check), but a contended
36
+ * acquire does not refuse: it waits in ~10 ms polls for up to ~10 s (holds are milliseconds),
37
+ * then answers the `STATE_UNAVAILABLE` 'retry' shape. A racing reader that lands between the
38
+ * winner's O_EXCL create and its write sees an empty body and waits out the window, not a
39
+ * refusal (a create that crashed mid-write reaches the cap; the operator removes the file).
40
+ * There is no heartbeat: a crash mid-op is taken over on the next acquire (the stale lease is
41
+ * the dead-man's switch). The poll wait is synchronous (Atomics.wait parks the thread): a wait
42
+ * approaching the ~10 s cap parks the event loop, so this process's own lease timers do not
43
+ * beat during it and a long wait can age its own holder and lock leases — the designed
44
+ * degradation is the normal sweep: a process whose registration is swept dead stops new
45
+ * writes (`STATE_UNAVAILABLE`); holds are milliseconds, so reaching the cap needs a peer
46
+ * already stalled (a double-stall scenario).
47
+ * - `state.key` (0600, 32 random bytes, created on first boot): HKDF splits it into the AES-256-GCM
48
+ * plan key and the tenant-id HMAC key. It sits beside the ciphertext (risk register: move it to
49
+ * the environment or a KMS on multi-user hosts). Two processes can race the very first boot:
50
+ * the create stays O_EXCL + write (renaming over the file would clobber the key), and the reader
51
+ * tolerates a partially written key (a short read is re-read for up to a second).
52
+ * - `plans/<handle>` (0600): one AES-256-GCM record per allowed preview, the handle as associated
53
+ * data. GCM authenticates the record, so an edited, truncated or swapped file fails to decrypt
54
+ * and reads as absent (`PLAN_NOT_FOUND`); payload args and PII are unreadable at rest. The
55
+ * random handles make concurrent saves collision-free.
56
+ * - `ledger.jsonl` (0600): the idempotency ledger — the single source of truth, re-read from disk
57
+ * on every lookup/count. Appends are one O_APPEND line (open, write, fsync, close): there is no
58
+ * persistent append fd, because a boot-rewrite rename would orphan a peer's open descriptor on
59
+ * a different inode. Every line carries the writer's `boot` and `pid`; entries still `sending`
60
+ * at boot become `unknown` when their origin is not a live holder; 14-day retention, pruned at
61
+ * boot (under the op lock). A torn final line (a peer crashed mid-append) is dropped by the
62
+ * fresh reads, never counted bad (the boot rewrite is the authority that counts).
63
+ * - `audit.jsonl` (0600): append-only JSONL, op, target ids, plan hash, decision and reason codes;
64
+ * never payloads or credentials. Every fsynced append runs under the shared op lock.
65
+ * - `KILL` (or `AUTOTASK_KILL_FILE`): its existence stops every preview and apply; any change to it
66
+ * (created, touched, removed) fires `onKill` (issue #311).
67
+ */
68
+ import { createHmac, hkdfSync } from 'node:crypto';
69
+ import { existsSync, mkdirSync, statSync } from 'node:fs';
70
+ import { join } from 'node:path';
71
+ import { canonicalJson } from './canonical.js';
72
+ import { OP_LOCK_WAIT_MS } from './store/constants.js';
73
+ import { LOOSE_MODE, refuse, stateKey, handle } from './store/files.js';
74
+ import { registerHolder, releaseHolder, sweepHolders, takeLock } from './store/lock.js';
75
+ import { createOpLock } from './store/op-lock.js';
76
+ import { createAuditLog } from './store/audit-log.js';
77
+ import { bootRewrite, createLedger } from './store/ledger.js';
78
+ import { createPlanStore } from './store/plan-store.js';
79
+ import { startHeartbeat } from './store/heartbeat.js';
80
+ import { auditTakeover, createBlocked, lockInfoOf, releasePrimaryLock, watchKillFile } from './store/lifecycle.js';
81
+ export { PLAN_TTL_MS, LEDGER_RETENTION_MS, COOLDOWN_MS, COOLDOWN_MINUTES, LEASE_REFRESH_MS, LEASE_EXPIRY_MS, OP_LOCK_POLL_MS, OP_LOCK_WAIT_MS } from './store/constants.js';
82
+ export { planKeyFrom, decryptPlan } from './store/plans.js';
83
+ /** Open (or create) the state directory; throws ConfigError on every boot refusal. */
84
+ export function openStateStore(dir, opts) {
85
+ const { log } = opts;
86
+ const now = opts.now ?? Date.now;
87
+ const opLockWaitMs = opts.opLockWaitMs ?? OP_LOCK_WAIT_MS;
88
+ if (!existsSync(dir))
89
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
90
+ const st = statSync(dir);
91
+ if (!st.isDirectory())
92
+ refuse(`${dir} is not a directory`);
93
+ if ((st.mode & LOOSE_MODE) !== 0)
94
+ refuse(`${dir} must be mode 0700 (it holds plans, the ledger and the audit log)`);
95
+ // ---- holder registry: register this boot BEFORE any other state work, sweep the dead peers ----
96
+ const holdersDir = join(dir, 'holders');
97
+ const myHolder = registerHolder(holdersDir, now);
98
+ // A boot refused after the registration must not leak the pair (issue #68 review N1):
99
+ // close() never runs when openStateStore throws, so the catch clears the heartbeat (if it
100
+ // started) and releases the process-scoped ref — the files go with the last ref.
101
+ let leaseTimer;
102
+ let killWatch = undefined;
103
+ try {
104
+ sweepHolders(holdersDir, log, now);
105
+ // ---- the primary lock: taken over when its holder is dead, kept (and this process boots as a
106
+ // secondary under it) when its holder is live (issue #68) ----
107
+ const lockPath = join(dir, 'lock');
108
+ const leasePath = join(dir, 'lock.lease');
109
+ const { takeover, ownsLock } = takeLock(lockPath, log, now, opLockWaitMs);
110
+ // ---- the per-operation lock (issue #68): the short critical sections that make sharing safe ----
111
+ const opLock = createOpLock({ dir, now, opLockWaitMs });
112
+ const acquireOpLock = opLock.acquire;
113
+ const releaseOpLock = opLock.release;
114
+ const key = stateKey(join(dir, 'state.key'), now);
115
+ const tenantKey = Buffer.from(hkdfSync('sha256', key, Buffer.alloc(0), 'iit-mcp-autotask tenant id', 32));
116
+ const planStore = createPlanStore({ dir, key, now });
117
+ const ledgerPath = join(dir, 'ledger.jsonl');
118
+ const auditPath = join(dir, 'audit.jsonl');
119
+ bootRewrite({ ledgerPath, auditPath, holdersDir, opLock, now, log });
120
+ const auditLog = createAuditLog({ auditPath, log, opLock, isClosed: () => closed });
121
+ const ledger = createLedger({ ledgerPath });
122
+ const killFile = opts.killFile ?? join(dir, 'KILL');
123
+ let applyQueue = Promise.resolve();
124
+ let closed = false;
125
+ // The heartbeats (issue #55 + #68), see `store/heartbeat.ts`; close() clears the timer.
126
+ leaseTimer = startHeartbeat({ myHolder, lockPath, leasePath, ownsLock, log, now });
127
+ killWatch = watchKillFile(killFile, opts.onKill, log);
128
+ const store = {
129
+ dir,
130
+ tenantId: (identity) => `tnt_${createHmac('sha256', tenantKey).update(canonicalJson(identity)).digest('hex')}`,
131
+ newHandle: handle,
132
+ savePlan: planStore.savePlan,
133
+ loadPlan: planStore.loadPlan,
134
+ lookup: ledger.lookup,
135
+ append: ledger.append,
136
+ counters: ledger.counters,
137
+ coolingDown: ledger.coolingDown,
138
+ audit: (event, at) => auditLog.append(event, at),
139
+ lockInfo: () => lockInfoOf({ lockPath, leasePath, holdersDir, now }),
140
+ // Writes also stop when this process's own holder registration disappears at runtime
141
+ // (issue #68): a primary lock being replaced by another boot NEVER blocks this process's
142
+ // writes — the op lock and the fresh reads make the sharing safe.
143
+ blocked: createBlocked({ killFile, myHolder, log, isClosed: () => closed, ...(opts.onKill !== undefined ? { onKill: opts.onKill } : {}) }),
144
+ killed() {
145
+ return this.blocked() !== undefined;
146
+ },
147
+ acquireOpLock,
148
+ releaseOpLock,
149
+ withApplyLock(fn) {
150
+ const run = applyQueue.then(fn, fn);
151
+ applyQueue = run.catch(() => undefined);
152
+ return run;
153
+ },
154
+ close() {
155
+ if (closed)
156
+ return;
157
+ closed = true;
158
+ clearInterval(leaseTimer);
159
+ killWatch?.close();
160
+ // Release this store's ref on the registration (issue #68): the file goes when the last
161
+ // store of the process closes — the next boot's sweep treats it as gone, and a live
162
+ // peer's boot rewrite leaves ITS `sending` lines untouched.
163
+ releaseHolder(myHolder);
164
+ // Only the store that TOOK the lock releases it (and its lease): a secondary's close never
165
+ // touches the lock it does not own, and a second store of the same process must not release
166
+ // the lock its sibling still holds.
167
+ releasePrimaryLock({ ownsLock, lockPath, leasePath });
168
+ },
169
+ };
170
+ // The takeover is an audit event (issue #55): see `auditTakeover`.
171
+ auditTakeover(store, takeover, now);
172
+ return store;
173
+ }
174
+ catch (err) {
175
+ if (leaseTimer !== undefined)
176
+ clearInterval(leaseTimer);
177
+ killWatch?.close();
178
+ releaseHolder(myHolder);
179
+ throw err;
180
+ }
181
+ }
182
+ //# sourceMappingURL=store.js.map
@@ -0,0 +1,29 @@
1
+ # TO VERIFY: agentgateway request-transformation syntax and missing-claim behaviour are unverified; replace with the tested config (see docs/write-gate.md#verification).
2
+ #
3
+ # Intent: for every request to the Autotask MCP server (AUTOTASK_HTTP_AUTH=gateway), the gateway
4
+ # 1. validates the caller's Entra JWT,
5
+ # 2. removes any x-autotask-client-id / x-autotask-principal the caller sent,
6
+ # 3. sets x-autotask-client-id from the JWT `azp` (falling back to `appid`) and
7
+ # x-autotask-principal from `oid`; a missing claim (has() guard) sets the header to "".
8
+ # The server treats a blank header as absent, so it then serves the request read-only
9
+ # (no principal). Client ids never bypass the server's MCP confirmation form.
10
+ binds:
11
+ - port: 3000
12
+ listeners:
13
+ - routes:
14
+ - policies:
15
+ jwtAuth:
16
+ issuer: https://login.microsoftonline.com/<tenant-id>/v2.0
17
+ audiences: [<api-app-id>]
18
+ jwks:
19
+ url: https://login.microsoftonline.com/<tenant-id>/discovery/v2.0/keys
20
+ transformations:
21
+ request:
22
+ remove:
23
+ - x-autotask-client-id
24
+ - x-autotask-principal
25
+ set:
26
+ x-autotask-client-id: 'has(jwt.azp) ? jwt.azp : (has(jwt.appid) ? jwt.appid : "")'
27
+ x-autotask-principal: 'has(jwt.oid) ? jwt.oid : ""'
28
+ backends:
29
+ - host: autotask-mcp:3000
package/package.json ADDED
@@ -0,0 +1,71 @@
1
+ {
2
+ "name": "iit-mcp-autotask",
3
+ "version": "0.54.2",
4
+ "description": "MCP server for the Autotask (Datto) PSA domain, built on the node-autotask SDK",
5
+ "license": "MIT",
6
+ "author": "Max Soukhomlinov",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/msoukhomlinov/iit-mcp-autotask.git"
10
+ },
11
+ "homepage": "https://github.com/msoukhomlinov/iit-mcp-autotask",
12
+ "keywords": [
13
+ "mcp",
14
+ "model-context-protocol",
15
+ "autotask",
16
+ "datto",
17
+ "psa"
18
+ ],
19
+ "type": "module",
20
+ "bin": {
21
+ "autotask-mcp": "dist/main.js"
22
+ },
23
+ "exports": {},
24
+ "files": [
25
+ "dist",
26
+ "!dist/**/*.map",
27
+ "skills/*.md",
28
+ "examples/*",
29
+ "README.md",
30
+ "LICENSE",
31
+ ".env.example",
32
+ "server.json",
33
+ "capabilities.json"
34
+ ],
35
+ "engines": {
36
+ "node": ">=24.0.0"
37
+ },
38
+ "scripts": {
39
+ "build": "tsc",
40
+ "start": "node dist/main.js",
41
+ "dev": "tsx src/main.ts",
42
+ "typecheck": "tsc --noEmit && tsc -p tsconfig.test.json",
43
+ "test": "vitest run",
44
+ "test:watch": "vitest",
45
+ "lint": "eslint src test",
46
+ "lint:fix": "eslint src test --fix",
47
+ "clean": "rimraf dist coverage",
48
+ "fresh-install-check": "bash scripts/fresh-install-check.sh",
49
+ "build:capabilities": "node scripts/build-capabilities.mjs",
50
+ "build:skills": "node scripts/build-skills.mjs",
51
+ "prepublish-check": "node scripts/prepublish-check.mjs",
52
+ "prepublishOnly": "npm run clean && npm run build && npm test && node scripts/prepublish-check.mjs",
53
+ "verify": "pnpm typecheck && pnpm lint && pnpm build && pnpm test && pnpm prepublish-check"
54
+ },
55
+ "dependencies": {
56
+ "@modelcontextprotocol/server": "^2.2.0",
57
+ "node-autotask": "0.56.1",
58
+ "zod": "^4.6.7"
59
+ },
60
+ "devDependencies": {
61
+ "@eslint/js": "^10.0.1",
62
+ "@types/node": "^24.19.1",
63
+ "eslint": "^10.14.0",
64
+ "globals": "^17.14.0",
65
+ "rimraf": "^6.0.1",
66
+ "tsx": "^4.19.0",
67
+ "typescript": "^6.0.3",
68
+ "typescript-eslint": "^8.72.1",
69
+ "vitest": "^5.0.5"
70
+ }
71
+ }
package/server.json ADDED
@@ -0,0 +1,69 @@
1
+ {
2
+ "name": "iit-mcp-autotask",
3
+ "version": "0.54.2",
4
+ "description": "MCP server for the Autotask (Datto) PSA API, powered by the node-autotask SDK",
5
+ "mcpProtocolBaseline": "2026-07-28",
6
+ "legacyProtocolFallback": "2025-11-25",
7
+ "transports": {
8
+ "streamableHttp": {
9
+ "endpoint": "/mcp"
10
+ },
11
+ "stdio": true
12
+ },
13
+ "endpoints": {
14
+ "health": "/health",
15
+ "ready": "/ready",
16
+ "doctor": "/doctor",
17
+ "metadata": "/metadata"
18
+ },
19
+ "stateless": true,
20
+ "statelessException": "SDK-owned per-tenant in-process client pool and read caching (AUTOTASK_CACHE=on|off), never cross-tenant or on disk. Operator deployments (AUTOTASK_PROFILE=operator or any operator token) hold encrypted plans, a write-ahead ledger and an append-only JSONL audit log in AUTOTASK_STATE_DIR, keyed by principal and tenant id, never by credential; many processes may share a state dir (holder registry + per-operation lock; a live primary admits a newcomer as a secondary) \u2014 see docs/architecture.md sections 7.3 and 8",
21
+ "credentialModel": "per-request",
22
+ "gatewayAssumptions": {
23
+ "appliesWhen": "AUTOTASK_HTTP_AUTH=gateway",
24
+ "handles": [
25
+ "client-authentication",
26
+ "rate-limiting",
27
+ "credential-injection"
28
+ ],
29
+ "otherwise": "AUTOTASK_HTTP_AUTH=tokens: this process authenticates bearer tokens and rate-limits per principal; on loopback with no caller auth, the bind is the boundary"
30
+ },
31
+ "profiles": {
32
+ "readonly": {
33
+ "default": true,
34
+ "stateful": false
35
+ },
36
+ "operator": {
37
+ "stateful": true,
38
+ "requires": [
39
+ "AUTOTASK_WRITE",
40
+ "AUTOTASK_STATE_DIR (0700, shareable by many processes)",
41
+ "a run scope per operator principal (AUTOTASK_RUN_SCOPE on stdio, runScope per token on HTTP)",
42
+ "AUTOTASK_HTTP_AUTH=tokens or gateway on HTTP",
43
+ "no AUTOTASK_ALLOW_ANY_BASE_HOST"
44
+ ],
45
+ "tools": [
46
+ "autotask_write",
47
+ "autotask_apply",
48
+ "autotask_apply_destructive"
49
+ ]
50
+ }
51
+ },
52
+ "toolsets": {
53
+ "core": "always on",
54
+ "optional": [
55
+ "service",
56
+ "records",
57
+ "finance"
58
+ ],
59
+ "select": "AUTOTASK_TOOLSETS (comma list or all)",
60
+ "operator": "operator profile only: autotask_write, autotask_apply, autotask_apply_destructive"
61
+ },
62
+ "capabilitiesManifest": "capabilities.json",
63
+ "sdk": {
64
+ "package": "node-autotask",
65
+ "versionRange": "0.56.1"
66
+ },
67
+ "vendorExtensions": false,
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 uses the credential on the apply request"
69
+ }