@onlyflows/servicenow-mcp 1.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (281) hide show
  1. package/.env.example +56 -0
  2. package/CHANGELOG.md +214 -0
  3. package/README.md +939 -101
  4. package/dist/auth.d.ts +88 -0
  5. package/dist/auth.d.ts.map +1 -0
  6. package/dist/auth.js +396 -0
  7. package/dist/auth.js.map +1 -0
  8. package/dist/client.d.ts +111 -17
  9. package/dist/client.d.ts.map +1 -1
  10. package/dist/client.js +554 -79
  11. package/dist/client.js.map +1 -1
  12. package/dist/config.d.ts +41 -4
  13. package/dist/config.d.ts.map +1 -1
  14. package/dist/config.js +44 -34
  15. package/dist/config.js.map +1 -1
  16. package/dist/encoded-query-policy.d.ts +72 -0
  17. package/dist/encoded-query-policy.d.ts.map +1 -0
  18. package/dist/encoded-query-policy.js +409 -0
  19. package/dist/encoded-query-policy.js.map +1 -0
  20. package/dist/execution-context.d.ts +235 -0
  21. package/dist/execution-context.d.ts.map +1 -0
  22. package/dist/execution-context.js +441 -0
  23. package/dist/execution-context.js.map +1 -0
  24. package/dist/field-policy.d.ts +117 -0
  25. package/dist/field-policy.d.ts.map +1 -0
  26. package/dist/field-policy.js +1684 -0
  27. package/dist/field-policy.js.map +1 -0
  28. package/dist/http-auth.d.ts +131 -0
  29. package/dist/http-auth.d.ts.map +1 -0
  30. package/dist/http-auth.js +347 -0
  31. package/dist/http-auth.js.map +1 -0
  32. package/dist/http-entrypoint.d.ts +26 -0
  33. package/dist/http-entrypoint.d.ts.map +1 -0
  34. package/dist/http-entrypoint.js +255 -0
  35. package/dist/http-entrypoint.js.map +1 -0
  36. package/dist/http-observability.d.ts +147 -0
  37. package/dist/http-observability.d.ts.map +1 -0
  38. package/dist/http-observability.js +711 -0
  39. package/dist/http-observability.js.map +1 -0
  40. package/dist/http-request-policy.d.ts +72 -0
  41. package/dist/http-request-policy.d.ts.map +1 -0
  42. package/dist/http-request-policy.js +463 -0
  43. package/dist/http-request-policy.js.map +1 -0
  44. package/dist/http-request-signal.d.ts +12 -0
  45. package/dist/http-request-signal.d.ts.map +1 -0
  46. package/dist/http-request-signal.js +39 -0
  47. package/dist/http-request-signal.js.map +1 -0
  48. package/dist/http-runtime.d.ts +77 -0
  49. package/dist/http-runtime.d.ts.map +1 -0
  50. package/dist/http-runtime.js +1321 -0
  51. package/dist/http-runtime.js.map +1 -0
  52. package/dist/incident-journal-policy.d.ts +22 -0
  53. package/dist/incident-journal-policy.d.ts.map +1 -0
  54. package/dist/incident-journal-policy.js +115 -0
  55. package/dist/incident-journal-policy.js.map +1 -0
  56. package/dist/index.d.ts +14 -4
  57. package/dist/index.d.ts.map +1 -1
  58. package/dist/index.js +140 -36
  59. package/dist/index.js.map +1 -1
  60. package/dist/metadata-cache.d.ts +71 -0
  61. package/dist/metadata-cache.d.ts.map +1 -0
  62. package/dist/metadata-cache.js +397 -0
  63. package/dist/metadata-cache.js.map +1 -0
  64. package/dist/profile-admin.d.ts +64 -0
  65. package/dist/profile-admin.d.ts.map +1 -0
  66. package/dist/profile-admin.js +351 -0
  67. package/dist/profile-admin.js.map +1 -0
  68. package/dist/profile-credentials.d.ts +68 -0
  69. package/dist/profile-credentials.d.ts.map +1 -0
  70. package/dist/profile-credentials.js +329 -0
  71. package/dist/profile-credentials.js.map +1 -0
  72. package/dist/profile-manager.d.ts +187 -0
  73. package/dist/profile-manager.d.ts.map +1 -0
  74. package/dist/profile-manager.js +1026 -0
  75. package/dist/profile-manager.js.map +1 -0
  76. package/dist/record-identifier-policy.d.ts +39 -0
  77. package/dist/record-identifier-policy.d.ts.map +1 -0
  78. package/dist/record-identifier-policy.js +203 -0
  79. package/dist/record-identifier-policy.js.map +1 -0
  80. package/dist/runtime-environment.d.ts +23 -0
  81. package/dist/runtime-environment.d.ts.map +1 -0
  82. package/dist/runtime-environment.js +58 -0
  83. package/dist/runtime-environment.js.map +1 -0
  84. package/dist/server.d.ts +33 -0
  85. package/dist/server.d.ts.map +1 -0
  86. package/dist/server.js +73 -0
  87. package/dist/server.js.map +1 -0
  88. package/dist/servicenow-identifiers.d.ts +8 -0
  89. package/dist/servicenow-identifiers.d.ts.map +1 -0
  90. package/dist/servicenow-identifiers.js +22 -0
  91. package/dist/servicenow-identifiers.js.map +1 -0
  92. package/dist/setup-prompts.d.ts +7 -0
  93. package/dist/setup-prompts.d.ts.map +1 -0
  94. package/dist/setup-prompts.js +123 -0
  95. package/dist/setup-prompts.js.map +1 -0
  96. package/dist/setup.d.ts +109 -0
  97. package/dist/setup.d.ts.map +1 -0
  98. package/dist/setup.js +1903 -0
  99. package/dist/setup.js.map +1 -0
  100. package/dist/startup.d.ts +43 -0
  101. package/dist/startup.d.ts.map +1 -0
  102. package/dist/startup.js +75 -0
  103. package/dist/startup.js.map +1 -0
  104. package/dist/stdio-runtime.d.ts +106 -0
  105. package/dist/stdio-runtime.d.ts.map +1 -0
  106. package/dist/stdio-runtime.js +231 -0
  107. package/dist/stdio-runtime.js.map +1 -0
  108. package/dist/structured-query.d.ts +187 -0
  109. package/dist/structured-query.d.ts.map +1 -0
  110. package/dist/structured-query.js +503 -0
  111. package/dist/structured-query.js.map +1 -0
  112. package/dist/table-defaults.d.ts +28 -0
  113. package/dist/table-defaults.d.ts.map +1 -0
  114. package/dist/table-defaults.js +85 -0
  115. package/dist/table-defaults.js.map +1 -0
  116. package/dist/table-policy.d.ts +71 -0
  117. package/dist/table-policy.d.ts.map +1 -0
  118. package/dist/table-policy.js +290 -0
  119. package/dist/table-policy.js.map +1 -0
  120. package/dist/tool-error.d.ts +48 -0
  121. package/dist/tool-error.d.ts.map +1 -0
  122. package/dist/tool-error.js +139 -0
  123. package/dist/tool-error.js.map +1 -0
  124. package/dist/tool-table-access.d.ts +19 -0
  125. package/dist/tool-table-access.d.ts.map +1 -0
  126. package/dist/tool-table-access.js +388 -0
  127. package/dist/tool-table-access.js.map +1 -0
  128. package/dist/tools/aggregate.d.ts +22 -42
  129. package/dist/tools/aggregate.d.ts.map +1 -1
  130. package/dist/tools/aggregate.js +103 -47
  131. package/dist/tools/aggregate.js.map +1 -1
  132. package/dist/tools/all-fields-cap.d.ts +45 -0
  133. package/dist/tools/all-fields-cap.d.ts.map +1 -0
  134. package/dist/tools/all-fields-cap.js +151 -0
  135. package/dist/tools/all-fields-cap.js.map +1 -0
  136. package/dist/tools/atf.d.ts +21 -60
  137. package/dist/tools/atf.d.ts.map +1 -1
  138. package/dist/tools/atf.js +180 -116
  139. package/dist/tools/atf.js.map +1 -1
  140. package/dist/tools/attach.d.ts +31 -45
  141. package/dist/tools/attach.d.ts.map +1 -1
  142. package/dist/tools/attach.js +175 -137
  143. package/dist/tools/attach.js.map +1 -1
  144. package/dist/tools/batch.d.ts +78 -42
  145. package/dist/tools/batch.d.ts.map +1 -1
  146. package/dist/tools/batch.js +172 -68
  147. package/dist/tools/batch.js.map +1 -1
  148. package/dist/tools/catalog.d.ts +6 -0
  149. package/dist/tools/catalog.d.ts.map +1 -0
  150. package/dist/tools/catalog.js +203 -0
  151. package/dist/tools/catalog.js.map +1 -0
  152. package/dist/tools/codesearch.d.ts +14 -25
  153. package/dist/tools/codesearch.d.ts.map +1 -1
  154. package/dist/tools/codesearch.js +60 -48
  155. package/dist/tools/codesearch.js.map +1 -1
  156. package/dist/tools/create-module.d.ts +48 -0
  157. package/dist/tools/create-module.d.ts.map +1 -0
  158. package/dist/tools/create-module.js +98 -0
  159. package/dist/tools/create-module.js.map +1 -0
  160. package/dist/tools/create.d.ts +2 -38
  161. package/dist/tools/create.d.ts.map +1 -1
  162. package/dist/tools/create.js +9 -41
  163. package/dist/tools/create.js.map +1 -1
  164. package/dist/tools/delete.d.ts +13 -23
  165. package/dist/tools/delete.d.ts.map +1 -1
  166. package/dist/tools/delete.js +30 -33
  167. package/dist/tools/delete.js.map +1 -1
  168. package/dist/tools/discover.d.ts +15 -27
  169. package/dist/tools/discover.d.ts.map +1 -1
  170. package/dist/tools/discover.js +103 -60
  171. package/dist/tools/discover.js.map +1 -1
  172. package/dist/tools/get-module.d.ts +85 -0
  173. package/dist/tools/get-module.d.ts.map +1 -0
  174. package/dist/tools/get-module.js +221 -0
  175. package/dist/tools/get-module.js.map +1 -0
  176. package/dist/tools/get.d.ts +2 -51
  177. package/dist/tools/get.d.ts.map +1 -1
  178. package/dist/tools/get.js +9 -49
  179. package/dist/tools/get.js.map +1 -1
  180. package/dist/tools/handler-result.d.ts +14 -0
  181. package/dist/tools/handler-result.d.ts.map +1 -0
  182. package/dist/tools/handler-result.js +177 -0
  183. package/dist/tools/handler-result.js.map +1 -0
  184. package/dist/tools/health.d.ts +12 -15
  185. package/dist/tools/health.d.ts.map +1 -1
  186. package/dist/tools/health.js +55 -36
  187. package/dist/tools/health.js.map +1 -1
  188. package/dist/tools/incident-journal-module.d.ts +12 -0
  189. package/dist/tools/incident-journal-module.d.ts.map +1 -0
  190. package/dist/tools/incident-journal-module.js +61 -0
  191. package/dist/tools/incident-journal-module.js.map +1 -0
  192. package/dist/tools/index.d.ts +47 -36
  193. package/dist/tools/index.d.ts.map +1 -1
  194. package/dist/tools/index.js +814 -35
  195. package/dist/tools/index.js.map +1 -1
  196. package/dist/tools/nl.d.ts +10 -24
  197. package/dist/tools/nl.d.ts.map +1 -1
  198. package/dist/tools/nl.js +37 -147
  199. package/dist/tools/nl.js.map +1 -1
  200. package/dist/tools/profile.d.ts +37 -0
  201. package/dist/tools/profile.d.ts.map +1 -0
  202. package/dist/tools/profile.js +39 -0
  203. package/dist/tools/profile.js.map +1 -0
  204. package/dist/tools/query-module.d.ts +119 -0
  205. package/dist/tools/query-module.d.ts.map +1 -0
  206. package/dist/tools/query-module.js +324 -0
  207. package/dist/tools/query-module.js.map +1 -0
  208. package/dist/tools/query.d.ts +2 -72
  209. package/dist/tools/query.d.ts.map +1 -1
  210. package/dist/tools/query.js +8 -72
  211. package/dist/tools/query.js.map +1 -1
  212. package/dist/tools/record-write-shared.d.ts +7 -0
  213. package/dist/tools/record-write-shared.d.ts.map +1 -0
  214. package/dist/tools/record-write-shared.js +65 -0
  215. package/dist/tools/record-write-shared.js.map +1 -0
  216. package/dist/tools/relationships.d.ts +21 -42
  217. package/dist/tools/relationships.d.ts.map +1 -1
  218. package/dist/tools/relationships.js +70 -56
  219. package/dist/tools/relationships.js.map +1 -1
  220. package/dist/tools/result-envelope.d.ts +603 -0
  221. package/dist/tools/result-envelope.d.ts.map +1 -0
  222. package/dist/tools/result-envelope.js +770 -0
  223. package/dist/tools/result-envelope.js.map +1 -0
  224. package/dist/tools/schema-module.d.ts +64 -0
  225. package/dist/tools/schema-module.d.ts.map +1 -0
  226. package/dist/tools/schema-module.js +367 -0
  227. package/dist/tools/schema-module.js.map +1 -0
  228. package/dist/tools/schema.d.ts +2 -37
  229. package/dist/tools/schema.d.ts.map +1 -1
  230. package/dist/tools/schema.js +6 -57
  231. package/dist/tools/schema.js.map +1 -1
  232. package/dist/tools/script.d.ts +33 -27
  233. package/dist/tools/script.d.ts.map +1 -1
  234. package/dist/tools/script.js +43 -37
  235. package/dist/tools/script.js.map +1 -1
  236. package/dist/tools/syslog.d.ts +19 -46
  237. package/dist/tools/syslog.d.ts.map +1 -1
  238. package/dist/tools/syslog.js +101 -67
  239. package/dist/tools/syslog.js.map +1 -1
  240. package/dist/tools/tool-module.d.ts +143 -0
  241. package/dist/tools/tool-module.d.ts.map +1 -0
  242. package/dist/tools/tool-module.js +1095 -0
  243. package/dist/tools/tool-module.js.map +1 -0
  244. package/dist/tools/update-module.d.ts +51 -0
  245. package/dist/tools/update-module.d.ts.map +1 -0
  246. package/dist/tools/update-module.js +111 -0
  247. package/dist/tools/update-module.js.map +1 -0
  248. package/dist/tools/update.d.ts +2 -45
  249. package/dist/tools/update.d.ts.map +1 -1
  250. package/dist/tools/update.js +9 -41
  251. package/dist/tools/update.js.map +1 -1
  252. package/dist/utils.d.ts +68 -1
  253. package/dist/utils.d.ts.map +1 -1
  254. package/dist/utils.js +114 -16
  255. package/dist/utils.js.map +1 -1
  256. package/dist/version.d.ts +10 -0
  257. package/dist/version.d.ts.map +1 -0
  258. package/dist/version.js +13 -0
  259. package/dist/version.js.map +1 -0
  260. package/dist/write-value-policy.d.ts +56 -0
  261. package/dist/write-value-policy.d.ts.map +1 -0
  262. package/dist/write-value-policy.js +310 -0
  263. package/dist/write-value-policy.js.map +1 -0
  264. package/docs/ADDING-TOOLS.md +227 -0
  265. package/docs/CLIENT-SETUP.md +914 -0
  266. package/docs/CONTAINER-DEPLOYMENT.md +310 -0
  267. package/docs/CROSS-CLIENT-RELEASE-MATRIX.md +63 -0
  268. package/docs/ENTERPRISE-RELEASE-BOUNDARY.md +149 -0
  269. package/docs/OPERATIONS-RUNBOOK.md +383 -0
  270. package/docs/PRIVATE-CHATGPT-CONNECTIVITY.md +347 -0
  271. package/docs/PRODUCTION-SECURITY.md +368 -0
  272. package/docs/PROFILE-CREDENTIALS.md +126 -0
  273. package/docs/RELEASE-VALIDATION.md +140 -0
  274. package/docs/TESTING-OAUTH.md +101 -0
  275. package/docs/V2-MIGRATION.md +493 -0
  276. package/package.json +60 -13
  277. package/scripts/inspector.mjs +140 -0
  278. package/scripts/release-validate.mjs +201 -0
  279. package/scripts/smoke-test.mjs +274 -0
  280. package/tools/inspector/package-lock.json +3812 -0
  281. package/tools/inspector/package.json +12 -0
package/dist/client.js CHANGED
@@ -2,51 +2,111 @@
2
2
  /**
3
3
  * ServiceNow HTTP client — native fetch-based, zero external dependencies.
4
4
  *
5
+ * Every request is bounded by an AbortSignal timeout and retried with
6
+ * exponential backoff + jitter on rate-limit / transient failures:
7
+ * - GET/PATCH/PUT/DELETE retry on 429, 502, 503, 504 and transient
8
+ * network errors (max 2 retries).
9
+ * - POST retries ONLY on 429 — a 429 is rejected before processing, so
10
+ * a retry is safe; a 5xx POST may have executed side effects.
11
+ * - Retry-After headers (delta-seconds and HTTP-date) are honored,
12
+ * capped at MAX_RETRY_DELAY_MS per wait.
13
+ * - A 401 triggers at most one AuthProvider refresh + retry.
14
+ *
5
15
  * @module client
6
16
  */
7
17
  Object.defineProperty(exports, "__esModule", { value: true });
8
- exports.ServiceNowClient = void 0;
18
+ exports.ServiceNowClient = exports.DEFAULT_MAX_CONCURRENT_REQUESTS = exports.BASIC_AUTH_401_HINT = exports.MAX_ERROR_RESPONSE_BYTES = exports.DEFAULT_MAX_JSON_RESPONSE_BYTES = exports.MAX_CUMULATIVE_RAW_RESPONSE_BYTES = exports.MAX_CUMULATIVE_UPSTREAM_JSON_BYTES = exports.MAX_RETRY_DELAY_MS = exports.DEFAULT_TIMEOUT_MS = void 0;
19
+ exports.runWithServiceNowRequestSignal = runWithServiceNowRequestSignal;
20
+ exports.createServiceNowOperations = createServiceNowOperations;
21
+ exports.parseRetryAfterMs = parseRetryAfterMs;
22
+ exports.retryDelayMs = retryDelayMs;
23
+ const node_async_hooks_1 = require("node:async_hooks");
24
+ const auth_js_1 = require("./auth.js");
25
+ const tool_error_js_1 = require("./tool-error.js");
26
+ exports.DEFAULT_TIMEOUT_MS = 30_000;
27
+ exports.MAX_RETRY_DELAY_MS = 30_000;
28
+ exports.MAX_CUMULATIVE_UPSTREAM_JSON_BYTES = 1024 * 1024;
29
+ exports.MAX_CUMULATIVE_RAW_RESPONSE_BYTES = 10 * 1024 * 1024;
30
+ exports.DEFAULT_MAX_JSON_RESPONSE_BYTES = exports.MAX_CUMULATIVE_UPSTREAM_JSON_BYTES;
31
+ exports.MAX_ERROR_RESPONSE_BYTES = 64 * 1024;
32
+ /** Guidance appended to 401 errors on basic-auth profiles. */
33
+ exports.BASIC_AUTH_401_HINT = "ServiceNow may be enforcing Basic Auth restrictions on this instance " +
34
+ "(see KB3096078). Exemptions: Web-Service-Access-Only account or " +
35
+ "snc_basic_auth_api_access role. Recommended: switch this profile to " +
36
+ "OAuth (authType: 'oauth').";
37
+ const DEFAULT_MAX_RETRIES = 2;
38
+ const DEFAULT_BASE_RETRY_DELAY_MS = 500;
39
+ exports.DEFAULT_MAX_CONCURRENT_REQUESTS = 4;
40
+ const MAX_CONFIGURED_CONCURRENT_REQUESTS = 32;
41
+ const RETRYABLE_STATUSES = [429, 502, 503, 504];
42
+ const REQUEST_SCOPE = new node_async_hooks_1.AsyncLocalStorage();
43
+ /**
44
+ * Bind one immutable execution-context signal and fresh atomic upstream byte
45
+ * budgets to cached clients without adding mutable state to the client/cache.
46
+ */
47
+ function runWithServiceNowRequestSignal(signal, operation) {
48
+ if (!(signal instanceof AbortSignal)) {
49
+ return Promise.reject(new TypeError("request signal must be an AbortSignal"));
50
+ }
51
+ if (typeof operation !== "function") {
52
+ return Promise.reject(new TypeError("request operation must be a function"));
53
+ }
54
+ try {
55
+ const scope = Object.freeze({
56
+ signal,
57
+ upstreamJsonBytes: new CumulativeResponseByteBudget(exports.MAX_CUMULATIVE_UPSTREAM_JSON_BYTES),
58
+ upstreamRawBytes: new CumulativeResponseByteBudget(exports.MAX_CUMULATIVE_RAW_RESPONSE_BYTES),
59
+ });
60
+ return Promise.resolve(REQUEST_SCOPE.run(scope, operation));
61
+ }
62
+ catch (error) {
63
+ return Promise.reject(error);
64
+ }
65
+ }
9
66
  class ServiceNowClient {
10
- config;
11
- baseUrl;
12
- authHeader;
13
- constructor(config) {
14
- this.config = config;
15
- this.baseUrl = config.instance;
16
- this.authHeader =
17
- "Basic " +
18
- Buffer.from(`${config.user}:${config.password}`).toString("base64");
67
+ #baseUrl;
68
+ #auth;
69
+ #timeoutMs;
70
+ #maxRetries;
71
+ #baseRetryDelayMs;
72
+ #sleep;
73
+ #limiter;
74
+ constructor(config, options = {}) {
75
+ this.#baseUrl = config.instance;
76
+ this.#auth = options.auth ?? (0, auth_js_1.createAuthProvider)(config);
77
+ this.#timeoutMs = config.timeoutMs ?? exports.DEFAULT_TIMEOUT_MS;
78
+ this.#maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
79
+ this.#baseRetryDelayMs = options.baseRetryDelayMs ?? DEFAULT_BASE_RETRY_DELAY_MS;
80
+ this.#sleep = options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
81
+ this.#limiter = limiterForOrigin(new URL(this.#baseUrl).origin, config.maxConcurrentRequests ?? exports.DEFAULT_MAX_CONCURRENT_REQUESTS);
19
82
  }
20
83
  // ── Core HTTP methods ──────────────────────────────────────────
21
84
  async get(path, params) {
22
- const url = this.buildUrl(path, params);
23
- return this.request("GET", url);
85
+ return (await this.requestWithMeta("GET", path, { params })).data;
86
+ }
87
+ /** GET that also exposes the response status + headers (e.g. X-Total-Count). */
88
+ async getWithMeta(path, params) {
89
+ return this.requestWithMeta("GET", path, { params });
24
90
  }
25
91
  async post(path, body) {
26
- const url = this.buildUrl(path);
27
- return this.request("POST", url, body);
92
+ return (await this.requestWithMeta("POST", path, { body })).data;
28
93
  }
29
94
  async patch(path, body) {
30
- const url = this.buildUrl(path);
31
- return this.request("PATCH", url, body);
95
+ return (await this.requestWithMeta("PATCH", path, { body })).data;
32
96
  }
33
97
  async put(path, body) {
34
- const url = this.buildUrl(path);
35
- return this.request("PUT", url, body);
98
+ return (await this.requestWithMeta("PUT", path, { body })).data;
36
99
  }
37
100
  async delete(path) {
38
101
  const url = this.buildUrl(path);
39
- const response = await fetch(url, {
40
- method: "DELETE",
41
- headers: {
42
- Authorization: this.authHeader,
43
- Accept: "application/json",
44
- },
102
+ const response = await this.fetchWithPolicy("DELETE", url, {
103
+ Accept: "application/json",
45
104
  });
46
105
  if (!response.ok && response.status !== 204) {
47
- const errorBody = await this.parseErrorBody(response);
48
- throw this.createError(errorBody?.message || `Delete failed with HTTP ${response.status}`, errorBody?.detail, response.status);
106
+ await this.consumeErrorBody(response);
107
+ throw this.buildHttpError("DELETE", response.status, response.headers);
49
108
  }
109
+ drainBody(response);
50
110
  return { status: response.status };
51
111
  }
52
112
  /**
@@ -54,42 +114,63 @@ class ServiceNowClient {
54
114
  */
55
115
  async postBinary(path, data, contentType, params) {
56
116
  const url = this.buildUrl(path, params);
57
- const response = await fetch(url, {
58
- method: "POST",
59
- headers: {
60
- Authorization: this.authHeader,
61
- Accept: "application/json",
62
- "Content-Type": contentType,
63
- },
64
- body: new Uint8Array(data),
65
- });
117
+ const response = await this.fetchWithPolicy("POST", url, {
118
+ Accept: "application/json",
119
+ "Content-Type": contentType,
120
+ }, new Uint8Array(data));
66
121
  if (!response.ok) {
67
- const errorBody = await this.parseErrorBody(response);
68
- throw this.createError(errorBody?.message || `Request failed with HTTP ${response.status}`, errorBody?.detail, response.status);
122
+ await this.consumeErrorBody(response);
123
+ throw this.buildHttpError("POST", response.status, response.headers);
69
124
  }
70
- return response.json();
125
+ return readJsonResponse(response, currentRequestSignal());
71
126
  }
72
127
  /**
73
128
  * GET raw response (for attachment downloads).
74
129
  */
75
- async getRaw(path) {
130
+ async getRaw(path, options = {}) {
76
131
  const url = this.buildUrl(path);
77
- const response = await fetch(url, {
78
- method: "GET",
79
- headers: {
80
- Authorization: this.authHeader,
81
- },
82
- });
132
+ const response = await this.fetchWithPolicy("GET", url, {});
83
133
  if (!response.ok) {
84
- throw this.createError(`Download failed with HTTP ${response.status}`, undefined, response.status);
134
+ drainBody(response);
135
+ throw this.buildHttpError("GET", response.status, response.headers);
85
136
  }
86
- const buffer = Buffer.from(await response.arrayBuffer());
137
+ const maximum = validateRawResponseLimit(options.maxBytes ?? exports.MAX_CUMULATIVE_RAW_RESPONSE_BYTES);
138
+ const buffer = await readBoundedResponseBody(response, maximum, currentRequestSignal(), currentRawByteBudget());
87
139
  const contentType = response.headers.get("content-type") || "application/octet-stream";
88
140
  return { data: buffer, contentType };
89
141
  }
142
+ /**
143
+ * Perform a JSON request and return the parsed body together with the
144
+ * response status and headers. The convenience methods above delegate here.
145
+ */
146
+ async requestWithMeta(method, path, options = {}) {
147
+ const url = this.buildUrl(path, options.params);
148
+ const response = await this.fetchWithPolicy(method, url, {
149
+ Accept: "application/json",
150
+ "Content-Type": "application/json",
151
+ }, options.body !== undefined ? JSON.stringify(options.body) : undefined);
152
+ if (!response.ok) {
153
+ await this.consumeErrorBody(response);
154
+ throw this.buildHttpError(method, response.status, response.headers);
155
+ }
156
+ // 204 No Content
157
+ if (response.status === 204) {
158
+ return { data: null, status: response.status, headers: response.headers };
159
+ }
160
+ return {
161
+ data: await readJsonResponse(response, currentRequestSignal()),
162
+ status: response.status,
163
+ headers: response.headers,
164
+ };
165
+ }
90
166
  // ── Internal helpers ───────────────────────────────────────────
91
167
  buildUrl(path, params) {
92
- const url = new URL(path, this.baseUrl);
168
+ validateServiceNowApiPath(path);
169
+ const url = new URL(path, this.#baseUrl);
170
+ const configuredOrigin = new URL(this.#baseUrl).origin;
171
+ if (url.origin !== configuredOrigin) {
172
+ throw new TypeError("ServiceNow API path must remain on the configured origin");
173
+ }
93
174
  if (params) {
94
175
  for (const [key, value] of Object.entries(params)) {
95
176
  if (value !== undefined && value !== "") {
@@ -99,47 +180,441 @@ class ServiceNowClient {
99
180
  }
100
181
  return url.toString();
101
182
  }
102
- async request(method, url, body) {
103
- const headers = {
104
- Authorization: this.authHeader,
105
- Accept: "application/json",
106
- "Content-Type": "application/json",
183
+ /**
184
+ * fetch() with the full request policy applied: auth headers, timeout,
185
+ * bounded retries with backoff, Retry-After, and a single 401
186
+ * refresh-and-retry via the AuthProvider.
187
+ */
188
+ async fetchWithPolicy(method, url, headers, body) {
189
+ let attempt = 0;
190
+ let authRetried = false;
191
+ for (;;) {
192
+ const requestSignal = currentRequestSignal();
193
+ throwIfRequestCancelled(requestSignal);
194
+ const authHeaders = await waitForRequestCancellation(this.#auth.getAuthHeaders(requestSignal), requestSignal);
195
+ let response;
196
+ const attemptTimeout = AbortSignal.timeout(this.#timeoutMs);
197
+ const attemptSignal = requestSignal
198
+ ? AbortSignal.any([requestSignal, attemptTimeout])
199
+ : attemptTimeout;
200
+ try {
201
+ response = await this.#limiter.run(() => fetch(url, {
202
+ method,
203
+ headers: { ...authHeaders, ...headers },
204
+ body,
205
+ signal: attemptSignal,
206
+ }));
207
+ }
208
+ catch {
209
+ if (requestSignal?.aborted)
210
+ throw requestCancellationError();
211
+ if (attemptTimeout.aborted) {
212
+ throw requestPolicyError("timeout", method);
213
+ }
214
+ // Transient network error (DNS, reset, refused...). Never retry a
215
+ // POST -- the request may have reached the server before failing.
216
+ if (method !== "POST" && attempt < this.#maxRetries) {
217
+ attempt++;
218
+ throwIfRequestCancelled(requestSignal);
219
+ await waitForRequestCancellation(this.#sleep(retryDelayMs(null, attempt, this.#baseRetryDelayMs)), requestSignal);
220
+ continue;
221
+ }
222
+ throw requestPolicyError("upstream", method);
223
+ }
224
+ // 401: give the auth provider one chance to refresh and retry.
225
+ if (response.status === 401 && !authRetried) {
226
+ throwIfRequestCancelled(requestSignal);
227
+ const shouldRetry = await waitForRequestCancellation(this.#auth.onAuthFailure(requestSignal), requestSignal);
228
+ if (shouldRetry) {
229
+ authRetried = true;
230
+ drainBody(response);
231
+ continue;
232
+ }
233
+ }
234
+ if (isRetryableStatus(response.status, method) &&
235
+ attempt < this.#maxRetries) {
236
+ attempt++;
237
+ const delay = retryDelayMs(response.headers.get("retry-after"), attempt, this.#baseRetryDelayMs);
238
+ drainBody(response);
239
+ throwIfRequestCancelled(requestSignal);
240
+ await waitForRequestCancellation(this.#sleep(delay), requestSignal);
241
+ continue;
242
+ }
243
+ return response;
244
+ }
245
+ }
246
+ async consumeErrorBody(response) {
247
+ try {
248
+ await readBoundedResponseText(response, exports.MAX_ERROR_RESPONSE_BYTES, currentRequestSignal(), currentUpstreamByteBudget());
249
+ }
250
+ catch (error) {
251
+ if (error instanceof ServiceNowRequestCancelledError)
252
+ throw error;
253
+ // A bounded/unreadable body never changes the structural HTTP map.
254
+ }
255
+ }
256
+ buildHttpError(method, status, headers) {
257
+ const classification = classifyHttpFailure(status, method);
258
+ const retryAfterSeconds = classification.retry === "retry_later"
259
+ ? (0, tool_error_js_1.boundedRetryAfterSeconds)(parseRetryAfterMs(headers.get("retry-after")))
260
+ : undefined;
261
+ return (0, tool_error_js_1.createToolError)(classification.category, classification.retry, retryAfterSeconds);
262
+ }
263
+ }
264
+ exports.ServiceNowClient = ServiceNowClient;
265
+ /** Build an immutable, reflection-safe capability around a resolved client. */
266
+ function createServiceNowOperations(client) {
267
+ const operations = Object.create(null);
268
+ Object.defineProperties(operations, {
269
+ get: {
270
+ value: (path, params) => client.get(path, params),
271
+ },
272
+ getWithMeta: {
273
+ value: (path, params) => client.getWithMeta(path, params),
274
+ },
275
+ post: {
276
+ value: (path, body) => client.post(path, body),
277
+ },
278
+ patch: {
279
+ value: (path, body) => client.patch(path, body),
280
+ },
281
+ delete: {
282
+ value: (path) => client.delete(path),
283
+ },
284
+ postBinary: {
285
+ value: (path, data, contentType, params) => client.postBinary(path, data, contentType, params),
286
+ },
287
+ getRaw: {
288
+ value: (path, options) => client.getRaw(path, options),
289
+ },
290
+ });
291
+ return Object.freeze(operations);
292
+ }
293
+ class UpstreamConcurrencyLimiter {
294
+ limit;
295
+ #active = 0;
296
+ #queue = [];
297
+ constructor(limit) {
298
+ this.limit = limit;
299
+ }
300
+ async run(operation) {
301
+ await this.acquire();
302
+ try {
303
+ return await operation();
304
+ }
305
+ finally {
306
+ this.release();
307
+ }
308
+ }
309
+ acquire() {
310
+ if (this.#active < this.limit) {
311
+ this.#active += 1;
312
+ return Promise.resolve();
313
+ }
314
+ return new Promise((resolve) => {
315
+ this.#queue.push(() => {
316
+ this.#active += 1;
317
+ resolve();
318
+ });
319
+ });
320
+ }
321
+ release() {
322
+ this.#active -= 1;
323
+ const next = this.#queue.shift();
324
+ if (next)
325
+ next();
326
+ }
327
+ }
328
+ const UPSTREAM_LIMITERS = new Map();
329
+ function limiterForOrigin(origin, configuredLimit) {
330
+ if (!Number.isSafeInteger(configuredLimit) ||
331
+ configuredLimit < 1 ||
332
+ configuredLimit > MAX_CONFIGURED_CONCURRENT_REQUESTS) {
333
+ throw new TypeError(`maxConcurrentRequests must be between 1 and ${MAX_CONFIGURED_CONCURRENT_REQUESTS}`);
334
+ }
335
+ const cached = UPSTREAM_LIMITERS.get(origin);
336
+ if (cached?.limit === configuredLimit)
337
+ return cached;
338
+ const limiter = new UpstreamConcurrencyLimiter(configuredLimit);
339
+ UPSTREAM_LIMITERS.set(origin, limiter);
340
+ return limiter;
341
+ }
342
+ function validateRawResponseLimit(candidate) {
343
+ if (typeof candidate !== "number" ||
344
+ !Number.isSafeInteger(candidate) ||
345
+ candidate < 1 ||
346
+ candidate > exports.MAX_CUMULATIVE_RAW_RESPONSE_BYTES) {
347
+ throw new TypeError("raw response maxBytes is invalid");
348
+ }
349
+ return candidate;
350
+ }
351
+ async function readBoundedResponseBody(response, maximum, signal, cumulativeBudget) {
352
+ const declaredLength = response.headers.get("content-length");
353
+ let reserved = 0;
354
+ let total = 0;
355
+ if (declaredLength !== null) {
356
+ const parsedLength = parseDeclaredContentLength(declaredLength);
357
+ if (parsedLength === undefined || parsedLength > maximum) {
358
+ try {
359
+ await response.body?.cancel("response exceeds configured byte limit");
360
+ }
361
+ catch {
362
+ // Cancellation is best effort after the response is rejected.
363
+ }
364
+ throw new RangeError("raw response exceeds configured byte limit");
365
+ }
366
+ if (cumulativeBudget) {
367
+ try {
368
+ cumulativeBudget.reserve(parsedLength);
369
+ reserved = parsedLength;
370
+ }
371
+ catch (error) {
372
+ try {
373
+ await response.body?.cancel("cumulative upstream byte limit exceeded");
374
+ }
375
+ catch {
376
+ // Cancellation is best effort after the response is rejected.
377
+ }
378
+ throw error;
379
+ }
380
+ }
381
+ }
382
+ if (!response.body) {
383
+ if (cumulativeBudget && reserved > 0)
384
+ cumulativeBudget.release(reserved);
385
+ return Buffer.alloc(0);
386
+ }
387
+ const reader = response.body.getReader();
388
+ const chunks = [];
389
+ try {
390
+ for (;;) {
391
+ throwIfRequestCancelled(signal);
392
+ const next = await waitForRequestCancellation(reader.read(), signal, () => {
393
+ void reader.cancel("request cancelled").catch(() => { });
394
+ });
395
+ if (next.done)
396
+ break;
397
+ const chunk = Buffer.from(next.value);
398
+ total += chunk.length;
399
+ if (total > maximum) {
400
+ await reader.cancel("response exceeds configured byte limit");
401
+ throw new RangeError("raw response exceeds configured byte limit");
402
+ }
403
+ if (cumulativeBudget && total > reserved) {
404
+ try {
405
+ cumulativeBudget.reserve(total - reserved);
406
+ reserved = total;
407
+ }
408
+ catch (error) {
409
+ await reader.cancel("cumulative upstream byte limit exceeded");
410
+ throw error;
411
+ }
412
+ }
413
+ chunks.push(chunk);
414
+ }
415
+ }
416
+ finally {
417
+ if (cumulativeBudget && reserved > total) {
418
+ cumulativeBudget.release(reserved - total);
419
+ }
420
+ reader.releaseLock();
421
+ }
422
+ return Buffer.concat(chunks, total);
423
+ }
424
+ class ServiceNowRequestCancelledError extends Error {
425
+ constructor() {
426
+ super("ServiceNow request cancelled");
427
+ this.name = "ServiceNowRequestCancelledError";
428
+ }
429
+ }
430
+ function currentRequestSignal() {
431
+ return REQUEST_SCOPE.getStore()?.signal;
432
+ }
433
+ function currentUpstreamByteBudget() {
434
+ return REQUEST_SCOPE.getStore()?.upstreamJsonBytes;
435
+ }
436
+ function currentRawByteBudget() {
437
+ return REQUEST_SCOPE.getStore()?.upstreamRawBytes;
438
+ }
439
+ function requestCancellationError() {
440
+ return new ServiceNowRequestCancelledError();
441
+ }
442
+ function throwIfRequestCancelled(signal) {
443
+ if (signal?.aborted)
444
+ throw requestCancellationError();
445
+ }
446
+ function waitForRequestCancellation(operation, signal, onAbort) {
447
+ if (!signal)
448
+ return operation;
449
+ if (signal.aborted) {
450
+ onAbort?.();
451
+ return Promise.reject(requestCancellationError());
452
+ }
453
+ return new Promise((resolve, reject) => {
454
+ const handleAbort = () => {
455
+ onAbort?.();
456
+ reject(requestCancellationError());
107
457
  };
108
- const response = await fetch(url, {
109
- method,
110
- headers,
111
- body: body ? JSON.stringify(body) : undefined,
458
+ signal.addEventListener("abort", handleAbort, { once: true });
459
+ void operation.then((value) => {
460
+ signal.removeEventListener("abort", handleAbort);
461
+ resolve(value);
462
+ }, (error) => {
463
+ signal.removeEventListener("abort", handleAbort);
464
+ reject(error);
112
465
  });
113
- if (!response.ok) {
114
- const errorBody = await this.parseErrorBody(response);
115
- throw this.createError(errorBody?.message || `Request failed with HTTP ${response.status}`, errorBody?.detail, response.status);
466
+ });
467
+ }
468
+ function readJsonResponse(response, signal) {
469
+ return readBoundedResponseText(response, exports.DEFAULT_MAX_JSON_RESPONSE_BYTES, signal, currentUpstreamByteBudget()).then((text) => JSON.parse(text));
470
+ }
471
+ async function readBoundedResponseText(response, maximum, signal, cumulativeBudget) {
472
+ const body = await readBoundedResponseBody(response, maximum, signal, cumulativeBudget);
473
+ throwIfRequestCancelled(signal);
474
+ return body.toString("utf8");
475
+ }
476
+ class CumulativeResponseByteBudget {
477
+ maximum;
478
+ #consumed = 0;
479
+ constructor(maximum) {
480
+ this.maximum = maximum;
481
+ }
482
+ reserve(bytes) {
483
+ if (!Number.isSafeInteger(bytes) || bytes < 0) {
484
+ throw new TypeError("upstream byte reservation is invalid");
116
485
  }
117
- // 204 No Content
118
- if (response.status === 204) {
119
- return null;
486
+ if (this.#consumed + bytes > this.maximum) {
487
+ throw new RangeError("cumulative upstream response exceeds configured byte limit");
488
+ }
489
+ this.#consumed += bytes;
490
+ }
491
+ release(bytes) {
492
+ if (!Number.isSafeInteger(bytes) || bytes < 0 || bytes > this.#consumed) {
493
+ throw new TypeError("upstream byte release is invalid");
120
494
  }
121
- return response.json();
495
+ this.#consumed -= bytes;
122
496
  }
123
- async parseErrorBody(response) {
497
+ }
498
+ function parseDeclaredContentLength(value) {
499
+ if (!/^(?:0|[1-9]\d*)$/u.test(value))
500
+ return undefined;
501
+ const parsed = Number(value);
502
+ return Number.isSafeInteger(parsed) ? parsed : undefined;
503
+ }
504
+ function validateServiceNowApiPath(candidate) {
505
+ if (typeof candidate !== "string" ||
506
+ !candidate.startsWith("/") ||
507
+ candidate.startsWith("//") ||
508
+ candidate.includes("\\") ||
509
+ candidate.includes("?") ||
510
+ candidate.includes("#")) {
511
+ throw new TypeError("ServiceNow API path must be an absolute path only");
512
+ }
513
+ const segments = candidate.split("/").slice(1);
514
+ if (segments.some((segment) => segment.length === 0)) {
515
+ throw new TypeError("ServiceNow API path contains an empty segment");
516
+ }
517
+ for (const segment of segments) {
518
+ let decoded;
124
519
  try {
125
- const text = await response.text();
126
- const json = JSON.parse(text);
127
- // ServiceNow error format
128
- if (json.error) {
129
- return {
130
- message: json.error.message || json.error,
131
- detail: json.error.detail,
132
- };
133
- }
134
- return { message: text };
520
+ decoded = decodeURIComponent(segment);
135
521
  }
136
522
  catch {
137
- return null;
523
+ throw new TypeError("ServiceNow API path contains invalid encoding");
524
+ }
525
+ if (decoded === "." ||
526
+ decoded === ".." ||
527
+ decoded.includes("/") ||
528
+ decoded.includes("\\") ||
529
+ /[\u0000-\u001F\u007F]/u.test(decoded)) {
530
+ throw new TypeError("ServiceNow API path contains an unsafe segment");
138
531
  }
139
532
  }
140
- createError(message, detail, status) {
141
- return { message, detail, status };
533
+ }
534
+ // ── Retry helpers (exported for tests) ─────────────────────────────
535
+ /**
536
+ * Parse a Retry-After header value into milliseconds.
537
+ * Supports both delta-seconds ("120") and HTTP-date forms.
538
+ * Returns undefined when the value is absent or unparseable.
539
+ */
540
+ function parseRetryAfterMs(value) {
541
+ if (!value)
542
+ return undefined;
543
+ const seconds = Number(value);
544
+ if (Number.isFinite(seconds)) {
545
+ return Math.max(0, seconds * 1000);
546
+ }
547
+ const dateMs = Date.parse(value);
548
+ if (!Number.isNaN(dateMs)) {
549
+ return Math.max(0, dateMs - Date.now());
550
+ }
551
+ return undefined;
552
+ }
553
+ /**
554
+ * Delay before retry `attempt` (1-based): the Retry-After header when
555
+ * present, otherwise exponential backoff with jitter. Capped at
556
+ * MAX_RETRY_DELAY_MS either way.
557
+ */
558
+ function retryDelayMs(retryAfter, attempt, baseDelayMs) {
559
+ const fromHeader = parseRetryAfterMs(retryAfter);
560
+ if (fromHeader !== undefined) {
561
+ return Math.min(fromHeader, exports.MAX_RETRY_DELAY_MS);
562
+ }
563
+ const backoff = baseDelayMs * 2 ** (attempt - 1) + Math.random() * baseDelayMs;
564
+ return Math.min(backoff, exports.MAX_RETRY_DELAY_MS);
565
+ }
566
+ // ── Module-level helpers ───────────────────────────────────────────
567
+ function isRetryableStatus(status, method) {
568
+ if (status === 429)
569
+ return true;
570
+ // A 5xx POST may have executed side effects on the instance -- never retry.
571
+ if (method === "POST")
572
+ return false;
573
+ return RETRYABLE_STATUSES.includes(status);
574
+ }
575
+ /** Map only trusted response status and request method into the public contract. */
576
+ function classifyHttpFailure(status, method) {
577
+ switch (status) {
578
+ case 401:
579
+ return { category: "authentication", retry: "retry_after_correction" };
580
+ case 403:
581
+ return { category: "authorization", retry: "retry_after_correction" };
582
+ case 404:
583
+ return { category: "not_found", retry: "do_not_retry" };
584
+ case 408:
585
+ return requestPolicyClassification("timeout", method);
586
+ case 409:
587
+ return { category: "conflict", retry: "retry_after_correction" };
588
+ case 429:
589
+ return { category: "rate_limit", retry: "retry_later" };
590
+ default:
591
+ // Other 4xx/3xx statuses are upstream rejections, but repeating the
592
+ // exact request is unsafe. 5xx failures may be retried only when the
593
+ // request method does not have ambiguous POST side effects.
594
+ return status >= 500
595
+ ? requestPolicyClassification("upstream", method)
596
+ : { category: "upstream", retry: "do_not_retry" };
597
+ }
598
+ }
599
+ function requestPolicyError(category, method) {
600
+ const classification = requestPolicyClassification(category, method);
601
+ return (0, tool_error_js_1.createToolError)(classification.category, classification.retry);
602
+ }
603
+ function requestPolicyClassification(category, method) {
604
+ return {
605
+ category,
606
+ retry: method === "POST"
607
+ ? "do_not_retry"
608
+ : "retry_if_safe_and_idempotent",
609
+ };
610
+ }
611
+ /** Release an unread response body so retried connections don't leak. */
612
+ function drainBody(response) {
613
+ try {
614
+ void response.body?.cancel();
615
+ }
616
+ catch {
617
+ // ignore -- best-effort cleanup
142
618
  }
143
619
  }
144
- exports.ServiceNowClient = ServiceNowClient;
145
620
  //# sourceMappingURL=client.js.map