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
package/dist/main.js ADDED
@@ -0,0 +1,283 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * main.ts — the process entry point: parse the CLI flags, validate config, build the logger,
4
+ * check the plan pin, pick a transport.
5
+ *
6
+ * The CLI carries ONLY operational flags (`--transport` / `--host` / `--port` / `--version` /
7
+ * `--help`) — no credential flags, ever (credentials are configuration: env under stdio,
8
+ * per-request headers under http). Nothing else lives here: both transports register the same
9
+ * tool surface from the same factory (`createMcpServerFactory`), so "which transport" is the
10
+ * only decision this file makes (the stdio transport is the few lines of `startStdio` below).
11
+ */
12
+ import { createMcpHandler } from '@modelcontextprotocol/server';
13
+ import { ConfigError } from './config/schema.js';
14
+ import { loadConfig, serverCredentialDefaults, unrecognisedAutotaskVars } from './config/load.js';
15
+ import { runDoctor } from './doctor.js';
16
+ import { createLogger } from './logger.js';
17
+ import { assertPlanHash } from './tools/catalog-data.js';
18
+ import { installHttpLifecycle } from './lifecycle.js';
19
+ import { startHttpServer } from './http.js';
20
+ import { loadTokenStore } from './http-guard.js';
21
+ import { serveStdio } from '@modelcontextprotocol/server/stdio';
22
+ import { createMcpServerFactory, SERVER_IDENTITY } from './tools/server.js';
23
+ import { describeSurface, selectSurface } from './tools/surface.js';
24
+ import { openWriteRuntime } from './write/runtime.js';
25
+ // The stdio transport: one process, one connection, no caller authentication. There is deliberately no
26
+ // shared secret: the process boundary IS the trust boundary (whoever can spawn this process already has
27
+ // the environment the credential comes from). stdout carries the protocol, so nothing may write there:
28
+ // the logger writes to stderr.
29
+ /**
30
+ * Serve MCP over this process's stdin/stdout.
31
+ *
32
+ * Returns the handle rather than awaiting anything: `serveStdio` owns the transport for the life of
33
+ * the process, and the caller needs the handle only to close it on a fatal error.
34
+ */
35
+ export function startStdio(config, log, write) {
36
+ const handle = serveStdio(createMcpServerFactory(config, log, write === undefined ? {} : { write }), {
37
+ // Reporting only — the SDK still answers the wire. Without this an out-of-band transport error
38
+ // is swallowed and the session simply goes quiet.
39
+ onerror: (err) => log.error('stdio transport error', { err: err.message }),
40
+ });
41
+ log.info('serving', { transport: 'stdio' });
42
+ return handle;
43
+ }
44
+ /** Minimal flag parse: `--flag value` and `--flag=value` forms; unknown flags are collected. */
45
+ function parseCliArgs(argv) {
46
+ const out = {};
47
+ for (let i = 0; i < argv.length; i++) {
48
+ const a = argv[i];
49
+ if (a === undefined)
50
+ continue;
51
+ if (a === '--version') {
52
+ out.version = true;
53
+ continue;
54
+ }
55
+ if (a === '--help' || a === '-h') {
56
+ out.help = true;
57
+ continue;
58
+ }
59
+ const forms = [['--transport', 'transport'], ['--host', 'host'], ['--port', 'port']];
60
+ let matched = false;
61
+ for (const [flag, key] of forms) {
62
+ if (a === flag) {
63
+ const value = argv[++i];
64
+ if (value !== undefined)
65
+ out[key] = value;
66
+ matched = true;
67
+ break;
68
+ }
69
+ if (a.startsWith(`${flag}=`)) {
70
+ out[key] = a.slice(flag.length + 1);
71
+ matched = true;
72
+ break;
73
+ }
74
+ }
75
+ if (!matched) {
76
+ out.unknown = out.unknown === undefined ? [a] : [...out.unknown, a];
77
+ }
78
+ }
79
+ return out;
80
+ }
81
+ const USAGE = `autotask-mcp — MCP server for the Autotask (Datto) PSA domain
82
+
83
+ Usage: autotask-mcp [flags]
84
+ doctor zero-wire credential/config preflight (no vendor request, ever);
85
+ exits 0 when everything would be accepted, 1 otherwise
86
+ --transport <stdio|http> the transport (default: $MCP_TRANSPORT, else http)
87
+ --host <address> the http bind address (default: $MCP_HOST, else 127.0.0.1;
88
+ off loopback, AUTOTASK_HTTP_ALLOWED_HOSTS and AUTOTASK_HTTP_AUTH
89
+ are required)
90
+ --port <number> the http listen port (default: $PORT, else 8080)
91
+ --version print the version and exit
92
+ --help this help
93
+
94
+ Credentials are configuration, never CLI flags: the environment under stdio, the per-request
95
+ X-Autotask-* headers under http (see the README configuration table).
96
+
97
+ Run \`autotask-mcp doctor\` before a live session: a green doctor means any later 401 is
98
+ vendor-side, not a mangled env load. See README §Credentials & env files.
99
+ `;
100
+ /**
101
+ * `doctor` — the zero-wire preflight subcommand (issue #5).
102
+ *
103
+ * Prints the credential shape report (length, two-character prefix, anomaly names; never a value),
104
+ * the base-url/allow-list resolution and the SDK plan-hash gate status, then exits. It is a
105
+ * SUBCOMMAND rather than a flag so it is unmistakable in a shell history and in a runbook, and it
106
+ * exits non-zero when something would be refused, so a deployment gate can use it directly.
107
+ *
108
+ * It dials nothing by construction — see `src/doctor.ts`, which imports no Autotask client. The
109
+ * whole point is that the question "did my credential load intact?" gets a cheap, local answer,
110
+ * because the alternative answer is a real auth failure against a vendor account where repeats
111
+ * risk a lock.
112
+ */
113
+ function runDoctorCommand() {
114
+ let config;
115
+ try {
116
+ config = loadConfig(process.env);
117
+ }
118
+ catch (err) {
119
+ if (err instanceof ConfigError) {
120
+ // The config refusal already names the variable, the anomaly and the load recipe — and
121
+ // never a value. It is JSON-wrapped so a runbook parses the same shape either way.
122
+ process.stdout.write(JSON.stringify({ ok: false, stage: 'config', error: err.message }, null, 2) + '\n');
123
+ process.exit(1);
124
+ }
125
+ throw err;
126
+ }
127
+ const report = runDoctor(config, process.env, describeSurface(config));
128
+ process.stdout.write(JSON.stringify(report, null, 2) + '\n');
129
+ // Non-zero: a runbook step (`doctor && live-run`) must stop on a bad credential, not proceed to
130
+ // the dial the report just said not to make.
131
+ process.exit(report.ok ? 0 : 1);
132
+ }
133
+ function main() {
134
+ // `doctor` is matched before anything else, so it never builds a logger, a transport or a client.
135
+ if (process.argv[2] === 'doctor') {
136
+ runDoctorCommand();
137
+ return;
138
+ }
139
+ const args = parseCliArgs(process.argv.slice(2));
140
+ // --version / --help predates the logger and the config: they print to stdout and exit 0.
141
+ // (Safe on stdout: no stdio MCP session starts before this point.)
142
+ if (args.version) {
143
+ process.stdout.write(`${SERVER_IDENTITY.name} ${SERVER_IDENTITY.version}\n`);
144
+ return;
145
+ }
146
+ if (args.help) {
147
+ process.stdout.write(USAGE);
148
+ return;
149
+ }
150
+ if (args.unknown !== undefined && args.unknown.length > 0) {
151
+ process.stderr.write(`unknown flag(s): ${args.unknown.join(' ')}\n\n${USAGE}`);
152
+ process.exit(2);
153
+ }
154
+ // The CLI's operational overrides merge into the environment-shaped record config reads:
155
+ // flag > env > default (see config/load.ts).
156
+ const env = { ...process.env };
157
+ if (args.transport !== undefined)
158
+ env.MCP_TRANSPORT = args.transport;
159
+ if (args.port !== undefined)
160
+ env.PORT = args.port;
161
+ if (args.host !== undefined)
162
+ env.MCP_HOST = args.host;
163
+ let config;
164
+ try {
165
+ config = loadConfig(env);
166
+ }
167
+ catch (err) {
168
+ // A config failure predates the logger, and its message names variables only — never a value.
169
+ // Exit non-zero so an orchestrator treats a mis-configured container as failed rather than
170
+ // healthy-but-useless.
171
+ if (err instanceof ConfigError) {
172
+ process.stderr.write(err.message + '\n');
173
+ process.exit(1);
174
+ }
175
+ throw err;
176
+ }
177
+ // FT-7 (security V27): the operational NDJSON sink is transport-aware — under http it is
178
+ // stdout (the container's log channel); under stdio, stdout IS the MCP protocol channel, so
179
+ // the logs must stay on stderr.
180
+ const logSink = config.MCP_TRANSPORT === 'http' ? process.stdout : process.stderr;
181
+ const log = createLogger(config.LOG_LEVEL, (line) => logSink.write(line + '\n'));
182
+ // Stale or mistyped AUTOTASK_* names are ignored, never a boot failure: say so once.
183
+ const unrecognised = unrecognisedAutotaskVars(env);
184
+ if (unrecognised.length > 0)
185
+ log.warn('ignoring unrecognised AUTOTASK_* variables (removed in an earlier version, or misspelled)', { variables: unrecognised });
186
+ // Security V9 (FT-3): the lab-only allow-any opt-in is a security-posture warning for the
187
+ // operator. It is NOT part of the operational NDJSON stream (under http that is stdout), so
188
+ // it goes straight to stderr on every transport — the stream an operator/monitor reads for
189
+ // warnings, not the log collector.
190
+ if (config.AUTOTASK_ALLOW_ANY_BASE_HOST) {
191
+ process.stderr.write(JSON.stringify({
192
+ ts: new Date().toISOString(),
193
+ level: 'warn',
194
+ msg: 'AUTOTASK_ALLOW_ANY_BASE_HOST=true: allow-any base-host mode is ACTIVE — any caller origin is admitted (lab mode; never set in production)',
195
+ }) + '\n');
196
+ }
197
+ // A surface that cannot be selected is a boot error, checked here before any listener binds.
198
+ try {
199
+ selectSurface(config);
200
+ }
201
+ catch (err) {
202
+ log.error('refusing to boot', { err: err instanceof Error ? err.message : String(err) });
203
+ process.exit(1);
204
+ }
205
+ // The drift gate (architecture 6.5): the installed SDK's plan must be the one this surface was
206
+ // built and reviewed against. A mismatch fails the boot with the named groups, before the
207
+ // listener binds.
208
+ try {
209
+ assertPlanHash();
210
+ }
211
+ catch (err) {
212
+ log.error('plan hash mismatch — refusing to boot', { err: err instanceof Error ? err.message : String(err) });
213
+ process.exit(1);
214
+ }
215
+ if (config.MCP_TRANSPORT === 'http' && serverCredentialDefaults(config) !== undefined) {
216
+ log.warn('http transport with server-held Autotask credential defaults: headerless requests run as that identity, presented to the default origin only');
217
+ }
218
+ if (config.MCP_TRANSPORT === 'stdio') {
219
+ const write = openWriteRuntimeOrExit(config, log);
220
+ const handle = startStdio(config, log, write);
221
+ process.on('uncaughtException', (err) => {
222
+ log.error('uncaught exception', { err: err instanceof Error ? (err.stack ?? err.message) : String(err) });
223
+ void handle.close().finally(() => process.exit(1));
224
+ });
225
+ // SIGTERM/SIGINT: close the transport and exit through process.exit, whose 'exit' hook
226
+ // releases the state dir (issue #68: a terminated process must not leave its holder
227
+ // registration behind for the next boot to sweep).
228
+ let stopping = false;
229
+ const stop = (signal) => {
230
+ if (stopping)
231
+ return; // a second signal mid-close: the first one is finishing it
232
+ stopping = true;
233
+ log.info('shutting down', { signal });
234
+ void handle.close().finally(() => process.exit(0));
235
+ };
236
+ process.on('SIGTERM', () => stop('SIGTERM'));
237
+ process.on('SIGINT', () => stop('SIGINT'));
238
+ return;
239
+ }
240
+ // tokens mode: the tokens file is read and validated once, before the listener binds.
241
+ let tokens;
242
+ if (config.AUTOTASK_HTTP_AUTH === 'tokens') {
243
+ try {
244
+ tokens = loadTokenStore(config.AUTOTASK_HTTP_TOKENS_FILE);
245
+ }
246
+ catch (err) {
247
+ log.error('refusing to boot', { err: err instanceof Error ? err.message : String(err) });
248
+ process.exit(1);
249
+ }
250
+ }
251
+ const write = openWriteRuntimeOrExit(config, log, tokens);
252
+ // The handler is built here and passed in: http.ts owns the listener, and deliberately knows
253
+ // nothing about tools.
254
+ const mcp = createMcpHandler(createMcpServerFactory(config, log, { ...(tokens !== undefined ? { tokens } : {}), ...(write !== undefined ? { write } : {}) }), {
255
+ onerror: (err) => log.error('mcp handler error', { err: err.message }),
256
+ });
257
+ // /ready reports the state lock's age, holder id and lease freshness when this is an operator
258
+ // deployment (issue #55); readonly deployments keep the fixed payload.
259
+ const server = startHttpServer(config, mcp, log, tokens, undefined, undefined, () => write?.store.lockInfo());
260
+ // Node's default SIGTERM handling is silent: install the process-level record of a killed
261
+ // container (crash, signal, clean exit all leave a line — see lifecycle.ts).
262
+ installHttpLifecycle(server, log);
263
+ }
264
+ /**
265
+ * The operator deployment's state (policy, state dir, lock): opened before anything serves, and a
266
+ * refusal exits non-zero. The lock is released on a normal exit; after a crash or a container
267
+ * replacement the next boot takes the lock over once the holder's lease is expired (3x the 5 s
268
+ * refresh) and audit-logs the takeover.
269
+ */
270
+ function openWriteRuntimeOrExit(config, log, tokens) {
271
+ try {
272
+ const write = openWriteRuntime(config, log, tokens);
273
+ if (write !== undefined)
274
+ process.on('exit', () => write.store.close());
275
+ return write;
276
+ }
277
+ catch (err) {
278
+ log.error('refusing to boot', { err: err instanceof Error ? err.message : String(err) });
279
+ process.exit(1);
280
+ }
281
+ }
282
+ main();
283
+ //# sourceMappingURL=main.js.map
@@ -0,0 +1,54 @@
1
+ /**
2
+ * policy.ts — the deployment's authority over which registry operations a call may reach,
3
+ * answered before any request is built.
4
+ *
5
+ * This module answers **whether** an operation is reachable in this deployment. It never answers
6
+ * **how** a call is performed: argument validation and the forced dry run stay in the SDK's invoke
7
+ * governor (`node-autotask/operations`). Deployment policy only narrows the SDK's mode and effect
8
+ * gates — it is a server-side pre-request gate, never a second governor.
9
+ *
10
+ * Two rules, both absolute for the life of the process:
11
+ * - **credential-minting** operations (`authenticate.*`: the response carries a live vendor auth
12
+ * token, which the SDK's redaction deliberately exempts) are never served, on any profile;
13
+ * - the read surface serves `effect: read` operations only. Writes belong to the operator
14
+ * profile's preview/apply path (`autotask_write`, `autotask_apply`), where AUTOTASK_WRITE
15
+ * decides; `refusalReason` reports that verdict for the catalog and `describe`.
16
+ *
17
+ * A policy refusal issues no Autotask request, so the SDK audit hook cannot see it — every
18
+ * refusal is logged here instead. The operation input bag is deliberately never logged: it can
19
+ * carry a credential (a create/patch payload with `password` / `secretKey`).
20
+ */
21
+ import { AutotaskConfigError } from 'node-autotask';
22
+ import type { CapabilityRecord } from 'node-autotask/capabilities';
23
+ import type { Config } from './config/schema.js';
24
+ import type { Logger } from './logger.js';
25
+ /** `write` and `destructive` are effects the read surface never dispatches. */
26
+ export declare function isWriteEffect(record: CapabilityRecord): boolean;
27
+ /**
28
+ * The credential-minting resources. Whole-resource matching, dot-anchored: any FUTURE
29
+ * `authenticate.*` operation arrives refused, not reachable-until-someone-notices.
30
+ */
31
+ export declare const CREDENTIAL_RESOURCES: readonly ["authenticate"];
32
+ /** Does `operation` sit on a credential-minting resource? */
33
+ export declare function isSecretOperation(operation: string): boolean;
34
+ /**
35
+ * The one-line reason `operation` is refused (for a catalog row or `describe`), or `null` when this
36
+ * deployment serves it. `writable` is the set of write operations the operator policy lists.
37
+ */
38
+ export declare function refusalReason(operation: string, record: CapabilityRecord | undefined, config: Config, writable?: ReadonlySet<string>): string | null;
39
+ /** The `POLICY_DENIED` error: deployment policy is fixed for the life of the process, so the
40
+ * model is told no argument it can choose will satisfy the gate (a `CONFIG_ERROR` here would
41
+ * invite the futile retry the policy-aware catalog exists to prevent). */
42
+ export declare class PolicyDeniedError extends AutotaskConfigError {
43
+ constructor(message: string, options?: {
44
+ operation?: string;
45
+ suggestedAction?: string;
46
+ });
47
+ }
48
+ /**
49
+ * Refuse an operation this deployment does not serve, before any request is built.
50
+ *
51
+ * Throws {@link PolicyDeniedError} (zero vendor wire). Logs one line per refusal — the operation
52
+ * key and effect, never the input bag (it can carry a credential).
53
+ */
54
+ export declare function assertOperationPermitted(operation: string, record: CapabilityRecord | undefined, config: Config, log: Logger): void;
package/dist/policy.js ADDED
@@ -0,0 +1,80 @@
1
+ /**
2
+ * policy.ts — the deployment's authority over which registry operations a call may reach,
3
+ * answered before any request is built.
4
+ *
5
+ * This module answers **whether** an operation is reachable in this deployment. It never answers
6
+ * **how** a call is performed: argument validation and the forced dry run stay in the SDK's invoke
7
+ * governor (`node-autotask/operations`). Deployment policy only narrows the SDK's mode and effect
8
+ * gates — it is a server-side pre-request gate, never a second governor.
9
+ *
10
+ * Two rules, both absolute for the life of the process:
11
+ * - **credential-minting** operations (`authenticate.*`: the response carries a live vendor auth
12
+ * token, which the SDK's redaction deliberately exempts) are never served, on any profile;
13
+ * - the read surface serves `effect: read` operations only. Writes belong to the operator
14
+ * profile's preview/apply path (`autotask_write`, `autotask_apply`), where AUTOTASK_WRITE
15
+ * decides; `refusalReason` reports that verdict for the catalog and `describe`.
16
+ *
17
+ * A policy refusal issues no Autotask request, so the SDK audit hook cannot see it — every
18
+ * refusal is logged here instead. The operation input bag is deliberately never logged: it can
19
+ * carry a credential (a create/patch payload with `password` / `secretKey`).
20
+ */
21
+ import { AutotaskConfigError } from 'node-autotask';
22
+ /** `write` and `destructive` are effects the read surface never dispatches. */
23
+ export function isWriteEffect(record) {
24
+ return record.effect === 'write' || record.effect === 'destructive';
25
+ }
26
+ /**
27
+ * The credential-minting resources. Whole-resource matching, dot-anchored: any FUTURE
28
+ * `authenticate.*` operation arrives refused, not reachable-until-someone-notices.
29
+ */
30
+ export const CREDENTIAL_RESOURCES = ['authenticate'];
31
+ /** Does `operation` sit on a credential-minting resource? */
32
+ export function isSecretOperation(operation) {
33
+ return CREDENTIAL_RESOURCES.some((resource) => operation.startsWith(`${resource}.`));
34
+ }
35
+ /**
36
+ * The one-line reason `operation` is refused (for a catalog row or `describe`), or `null` when this
37
+ * deployment serves it. `writable` is the set of write operations the operator policy lists.
38
+ */
39
+ export function refusalReason(operation, record, config, writable = new Set()) {
40
+ if (isSecretOperation(operation))
41
+ return 'refused: credential-minting operation (never served)';
42
+ if (record === undefined)
43
+ return 'refused: not in the capability registry';
44
+ if (record.effect === 'read')
45
+ return null;
46
+ if (config.AUTOTASK_PROFILE !== 'operator')
47
+ return 'refused: profile readonly serves reads only';
48
+ return writable.has(operation) ? null : 'refused: not in AUTOTASK_WRITE (unlisted writes are read-only)';
49
+ }
50
+ /** The `POLICY_DENIED` error: deployment policy is fixed for the life of the process, so the
51
+ * model is told no argument it can choose will satisfy the gate (a `CONFIG_ERROR` here would
52
+ * invite the futile retry the policy-aware catalog exists to prevent). */
53
+ export class PolicyDeniedError extends AutotaskConfigError {
54
+ constructor(message, options = {}) {
55
+ super(message, { code: 'POLICY_DENIED', category: 'policy', retryable: false, ...options });
56
+ this.name = 'PolicyDeniedError';
57
+ }
58
+ }
59
+ /**
60
+ * Refuse an operation this deployment does not serve, before any request is built.
61
+ *
62
+ * Throws {@link PolicyDeniedError} (zero vendor wire). Logs one line per refusal — the operation
63
+ * key and effect, never the input bag (it can carry a credential).
64
+ */
65
+ export function assertOperationPermitted(operation, record, config, log) {
66
+ // The read path never writes: a write is refused here on every profile (operator previews it
67
+ // through autotask_write instead).
68
+ const reason = record !== undefined && isWriteEffect(record) && !isSecretOperation(operation) && config.AUTOTASK_PROFILE === 'operator'
69
+ ? 'refused on the read path: preview a write with autotask_write'
70
+ : refusalReason(operation, record, config);
71
+ if (reason === null)
72
+ return;
73
+ const effect = record?.effect ?? 'unknown';
74
+ log.warn('operation refused by deployment policy', { operation, effect, profile: config.AUTOTASK_PROFILE });
75
+ throw new PolicyDeniedError(`${operation} (${effect}) is ${reason}. Reads of other operations are unaffected.`, {
76
+ operation,
77
+ suggestedAction: 'This deployment does not serve this operation; do not retry it.',
78
+ });
79
+ }
80
+ //# sourceMappingURL=policy.js.map
@@ -0,0 +1,16 @@
1
+ import type { ToolContext } from './context/types.js';
2
+ import { type ToolReturn } from './results/envelope.js';
3
+ /** The SDK aggregate opts this server passes (the SDK's own names). */
4
+ export interface AggregateOpts {
5
+ groupBy?: string[];
6
+ sum?: string[];
7
+ top?: number;
8
+ limit?: number;
9
+ /** false: no label siblings on the group keys (SDK default on). */
10
+ names?: boolean;
11
+ }
12
+ /**
13
+ * Counts, totals and group-by sums over one `<resource>.query` surface: `autotask_query` with
14
+ * group_by / sum / count (#228). `extra` rides the data.
15
+ */
16
+ export declare function runAggregate(ctx: ToolContext, operation: string, rawFilter: unknown, opts: AggregateOpts, signal: AbortSignal | undefined, extra?: Record<string, unknown>): Promise<ToolReturn>;
@@ -0,0 +1,64 @@
1
+ /**
2
+ * tools/aggregate.ts — the totals mode of `autotask_query` (`group_by` / `sum` / `count`; #197, #228):
3
+ * a thin wrapper over the SDK's `operations.aggregate`, so a roll-up question (totals, counts, group-by
4
+ * sums) is one call to a core tool, not a ~50 KB discovery trip through catalog, describe and read.
5
+ *
6
+ * Nothing is reimplemented: the SDK validates the operation, the field names and the caps (top 1-100,
7
+ * limit at most 2,500), folds the rows and reports its own truncation honesty (`hasMore`,
8
+ * `groupsTruncated`, `totalScanned`, `blind`); the answer passes through unchanged. What this adds is
9
+ * the gates every read passes (the deployment policy on both the helper and the target surface, the
10
+ * inbound untrusted-wrapper strip, the filter shape) and the untrusted marking of the answer by the
11
+ * TARGET resource's field stamps, the same list `autotask_read` of `<resource>.query` uses.
12
+ */
13
+ import { AutotaskConfigError } from 'node-autotask';
14
+ import { stripUntrustedDeep } from 'node-autotask/untrusted';
15
+ import { assertFilterShape } from './schemas.js';
16
+ import { abortedAnswer } from './dispatch.js';
17
+ import { markResult } from './results/untrusted.js';
18
+ import { ok } from './results/envelope.js';
19
+ import { assertOperationPermitted } from '../policy.js';
20
+ import { scopedCatalogCall } from './field-pointer.js';
21
+ /** The server line for an SDK aggregate answer: numbers only, and the partial marker whenever the SDK flags truncation. */
22
+ function summaryLine(operation, result) {
23
+ const r = (result ?? {});
24
+ if (r.mode === 'count' || typeof r.count === 'number') {
25
+ return `${operation}: ${typeof r.count === 'number' ? `${r.count} row(s) match` : 'counted'}.${r.blind === true || (r.blindSurface !== undefined && r.blindSurface !== false) ? ' blind: true (the surface cannot be counted, treat 0 as unknown).' : ''}`;
26
+ }
27
+ const scanned = typeof r.totalScanned === 'number' ? `${r.totalScanned} row(s) scanned` : 'rows scanned';
28
+ const groups = typeof r.totalGroups === 'number' ? `, ${r.totalGroups} group(s)` : '';
29
+ const partial = r.hasMore === true || r.groupsTruncated === true;
30
+ const blindNote = r.blindSurface !== undefined && r.blindSurface !== false ? ' blindSurface: the surface could not be read, an empty result is not a true zero.' : '';
31
+ return `${operation}: ${scanned}${groups}.${blindNote}${partial ? ' PARTIAL: the scan or the group list was cut short (hasMore / groupsTruncated); these are not tenant-wide totals, narrow the filter.' : ''}`;
32
+ }
33
+ /**
34
+ * Counts, totals and group-by sums over one `<resource>.query` surface: `autotask_query` with
35
+ * group_by / sum / count (#228). `extra` rides the data.
36
+ */
37
+ export async function runAggregate(ctx, operation, rawFilter, opts, signal, extra = {}) {
38
+ const helper = 'operations.aggregate';
39
+ assertOperationPermitted(helper, ctx.record(helper), ctx.config, ctx.log);
40
+ const target = ctx.record(operation);
41
+ if (target === undefined) {
42
+ throw new AutotaskConfigError(`aggregate: unknown operation "${operation}": it is not in the capability registry (find the exact key with autotask_catalog)`, { operation: helper });
43
+ }
44
+ assertOperationPermitted(operation, target, ctx.config, ctx.log);
45
+ assertFilterShape(rawFilter, helper);
46
+ // the conditions array (a params bag's own filter when the caller sent the bag form)
47
+ const conditions = Array.isArray(rawFilter) ? rawFilter : (rawFilter.filter ?? []);
48
+ const filter = stripUntrustedDeep(conditions);
49
+ // The SDK's positional form: [operation, filter] and the opts bag only when a fold or cap was set.
50
+ const bag = {};
51
+ for (const key of ['groupBy', 'sum', 'top', 'limit', 'names'])
52
+ if (opts[key] !== undefined)
53
+ bag[key] = opts[key];
54
+ const answer = await ctx.ops.invokeRead(ctx.client, helper, Object.keys(bag).length > 0 ? [operation, filter, bag] : [operation, filter], undefined, signal).catch((err) => {
55
+ // node-autotask #280: a bad filter / groupBy / sum name is a zero-wire CONFIG_ERROR; point at the scoped field catalog
56
+ if (!(err instanceof AutotaskConfigError) || !err.message.includes('is not a field of'))
57
+ throw err;
58
+ throw new AutotaskConfigError(err.message, { operation: helper, suggestedAction: `Use exact vendor field names: ${scopedCatalogCall(operation.slice(0, operation.indexOf('.')))}.` });
59
+ });
60
+ if (answer === undefined)
61
+ return abortedAnswer(ctx.correlationId);
62
+ return ok(summaryLine(operation, answer), { ...extra, operation, result: markResult(answer, ctx.untrustedFields(operation)) });
63
+ }
64
+ //# sourceMappingURL=aggregate.js.map
@@ -0,0 +1,4 @@
1
+ /** The manifest object (serialised with two-space indentation and a trailing newline). */
2
+ export declare function buildCapabilitiesManifest(): Record<string, unknown>;
3
+ /** The manifest file text, exactly as committed. */
4
+ export declare function capabilitiesManifestText(): string;
@@ -0,0 +1,94 @@
1
+ import { RECORDS, TOOL_NAME_BY_OP, toolDescription } from './catalog-data.js';
2
+ import { annotationsOf } from './register.js';
3
+ import { SURFACE, selectSurface } from './surface.js';
4
+ /** The canonical capability id per tool (`<domain>.<resource>.<verb>`). */
5
+ const CAPABILITY_IDS = {
6
+ autotask_guide: 'autotask.platform.guide',
7
+ autotask_catalog: 'autotask.platform.catalog',
8
+ autotask_describe: 'autotask.platform.describe',
9
+ autotask_read: 'autotask.generic.read',
10
+ autotask_resolve: 'autotask.discovery.resolve',
11
+ autotask_query: 'autotask.discovery.query',
12
+ autotask_tenant_status: 'autotask.identity.tenant_status',
13
+ autotask_ticket_full_context: 'autotask.ticket.full_context',
14
+ autotask_company_full_profile: 'autotask.company.full_profile',
15
+ autotask_project_get_context: 'autotask.project.get_context',
16
+ autotask_service_call_full_profile: 'autotask.service_call.full_profile',
17
+ autotask_resource_workload: 'autotask.resource.workload',
18
+ autotask_contact_full_profile: 'autotask.contact.full_profile',
19
+ autotask_configuration_item_profile: 'autotask.configuration_item.profile',
20
+ autotask_contract_full_profile: 'autotask.contract.full_profile',
21
+ autotask_quote_get: 'autotask.quote.get',
22
+ autotask_invoice_get: 'autotask.invoice.get',
23
+ autotask_write: 'autotask.generic.write',
24
+ autotask_apply: 'autotask.generic.apply',
25
+ autotask_apply_destructive: 'autotask.generic.apply_destructive',
26
+ };
27
+ /** What backs the tools that map no single registry operation. */
28
+ const BACKING = {
29
+ autotask_guide: 'packaged skills/*.md (static)',
30
+ autotask_catalog: 'node-autotask/capabilities registry + MCP_TOOL_CATALOG.json',
31
+ autotask_describe: 'registry records + operations.relationshipMap',
32
+ autotask_read: 'node-autotask/operations invokeRead (any effect=read key)',
33
+ autotask_write: 'node-autotask/operations invokeWrite / invokeDelete dry run (the keys AUTOTASK_WRITE lists)',
34
+ autotask_apply: 'node-autotask/operations invokeWrite / invokeDelete (exactly the previewed plan, no hard rule)',
35
+ autotask_apply_destructive: 'node-autotask/operations invokeWrite / invokeDelete (exactly the previewed plan that hits a hard rule)',
36
+ };
37
+ /** Operations a tool also calls that the catalog's `tool` column leaves to autotask_read (the ticket title search #162, the staff lookup #172). */
38
+ const ALSO_BACKED_BY = {
39
+ autotask_resolve: ['tickets.search', 'resources.query', 'resources.get', 'operations.fieldCatalog'],
40
+ };
41
+ /** The tool count each profile/toolset combination serves. */
42
+ function count(profile, toolsets) {
43
+ return selectSurface({ AUTOTASK_PROFILE: profile, AUTOTASK_TOOLSETS: toolsets }).length;
44
+ }
45
+ /** The manifest object (serialised with two-space indentation and a trailing newline). */
46
+ export function buildCapabilitiesManifest() {
47
+ const all = ['service', 'records', 'finance'];
48
+ return {
49
+ version: '0.4.0',
50
+ domain: 'autotask',
51
+ description: 'Machine-readable capability catalogue for iit-mcp-autotask: the tools the server can serve, with the toolset and the lowest profile that serves each. Everything else in the registry is reachable through the generic layer (autotask_catalog / autotask_describe / autotask_read) and documented in docs/capability-matrix.md. Generated from src/tools/surface.ts by scripts/build-capabilities.mjs.',
52
+ exposedToolCount: {
53
+ readonlyCore: count('readonly', []),
54
+ readonlyAll: count('readonly', all),
55
+ operatorCore: count('operator', []),
56
+ operatorAll: count('operator', all),
57
+ },
58
+ profiles: {
59
+ readonly: { note: 'Reads only. The default.' },
60
+ operator: { note: 'Adds the operator toolset (preview with autotask_write; execute with autotask_apply, or autotask_apply_destructive for a plan that hits a hard rule).' },
61
+ },
62
+ toolsets: Object.fromEntries(['core', 'service', 'records', 'finance', 'operator'].map((ts) => [ts, SURFACE.filter((t) => t.toolset === ts).map((t) => t.name)])),
63
+ naming: 'Tool names are snake_case, autotask_-prefixed (0.6.0 dropped the SDK manifest names: merged tools have no single manifest name). Writes preview through autotask_write and execute through autotask_apply, or autotask_apply_destructive when the plan hits a hard rule (deletes, webhook writes, approval-required ops, and moves that change company or contract); destructive operations preview through autotask_write too (deviation D-12).',
64
+ capabilities: SURFACE.map((t) => {
65
+ const ann = annotationsOf(t);
66
+ const ops = Object.entries(TOOL_NAME_BY_OP)
67
+ .filter(([, tool]) => tool === t.name)
68
+ .map(([op]) => op);
69
+ return {
70
+ id: CAPABILITY_IDS[t.name] ?? `autotask.${t.toolset}.${t.name.replace(/^autotask_/, '')}`,
71
+ description: toolDescription(t.name),
72
+ mcpPrimitive: 'tool',
73
+ toolName: t.name,
74
+ type: t.toolset === 'operator' ? 'write' : 'read',
75
+ toolset: t.toolset,
76
+ profile: t.profile,
77
+ backingOperation: BACKING[t.name] ?? [...ops, ...(ALSO_BACKED_BY[t.name] ?? [])].join(' | '),
78
+ annotations: { readOnly: ann.readOnlyHint, idempotent: ann.idempotentHint, destructive: ann.destructiveHint, openWorld: ann.openWorldHint },
79
+ };
80
+ }),
81
+ genericCapabilityLayer: {
82
+ enabled: true,
83
+ tools: ['autotask_catalog', 'autotask_describe', 'autotask_read'],
84
+ backingRegistryOperations: RECORDS.length,
85
+ note: 'autotask_catalog finds the exact operation key (ranked search), autotask_describe serves its contract, autotask_read runs any effect=read key. Writes go through the operator profile (autotask_write then autotask_apply); authenticate.* is never served.',
86
+ },
87
+ schemas: {},
88
+ };
89
+ }
90
+ /** The manifest file text, exactly as committed. */
91
+ export function capabilitiesManifestText() {
92
+ return `${JSON.stringify(buildCapabilitiesManifest(), null, 2)}\n`;
93
+ }
94
+ //# sourceMappingURL=capabilities-manifest.js.map