@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
@@ -0,0 +1,711 @@
1
+ "use strict";
2
+ /**
3
+ * Bounded, provider-neutral HTTP observability and rate-limit primitives.
4
+ *
5
+ * The public event inputs deliberately contain no request headers, URL/query,
6
+ * body, exception, credential, or token field. Identity values are represented
7
+ * by one-way digests in emitted events and rate-limit keys are retained only as
8
+ * digests. This makes accidental serialization of the HTTP authentication or
9
+ * ServiceNow credential surfaces structurally unavailable here.
10
+ *
11
+ * @module http-observability
12
+ */
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.MAX_RATE_LIMIT_ENTRIES = exports.MAX_RATE_LIMIT_PERIOD_MS = exports.MAX_RATE_LIMIT_CAPACITY = void 0;
15
+ exports.createHttpObservability = createHttpObservability;
16
+ exports.createJsonLinesEventSink = createJsonLinesEventSink;
17
+ exports.createBoundedJsonLinesEventSink = createBoundedJsonLinesEventSink;
18
+ exports.createHttpRateLimiter = createHttpRateLimiter;
19
+ exports.safeHttpRateLimitRejection = safeHttpRateLimitRejection;
20
+ const node_crypto_1 = require("node:crypto");
21
+ const tool_error_js_1 = require("./tool-error.js");
22
+ const EVENT_SCHEMA_VERSION = 1;
23
+ const MAX_LABEL_LENGTH = 128;
24
+ const MAX_ORIGIN_LENGTH = 2_048;
25
+ const MAX_LATENCY_MS = 7 * 24 * 60 * 60 * 1_000;
26
+ exports.MAX_RATE_LIMIT_CAPACITY = 1_000_000;
27
+ exports.MAX_RATE_LIMIT_PERIOD_MS = 24 * 60 * 60 * 1_000;
28
+ exports.MAX_RATE_LIMIT_ENTRIES = 100_000;
29
+ const MAX_RATE_LIMIT_KEY_LENGTH = 512;
30
+ const SAFE_TOOL_NAME = /^sn_[a-z0-9_]{1,61}$/u;
31
+ const UNSAFE_LOG_CHARACTER = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
32
+ const ISSUED_STRUCTURED_EVENTS = new WeakSet();
33
+ const ISSUED_RATE_LIMIT_DECISIONS = new WeakSet();
34
+ /** Create an observability boundary with deterministic, failure-isolated spans. */
35
+ function createHttpObservability(options) {
36
+ if (!options || typeof options !== "object") {
37
+ throw new TypeError("HTTP observability options must be an object");
38
+ }
39
+ const sink = options.sink;
40
+ if (!sink || typeof sink.write !== "function") {
41
+ throw new TypeError("HTTP observability sink must implement write");
42
+ }
43
+ const clock = options.clock ?? SYSTEM_CLOCK;
44
+ if (!clock || typeof clock.now !== "function") {
45
+ throw new TypeError("HTTP observability clock must implement now");
46
+ }
47
+ return Object.freeze({
48
+ beginRequest() {
49
+ const startedAt = safeNow(clock);
50
+ let finished = false;
51
+ return Object.freeze({
52
+ finish(completion) {
53
+ if (finished)
54
+ return undefined;
55
+ finished = true;
56
+ const endedAt = safeNow(clock, startedAt);
57
+ let event;
58
+ try {
59
+ event = createRequestEvent(completion, endedAt, boundedLatency(startedAt, endedAt));
60
+ }
61
+ catch {
62
+ return undefined;
63
+ }
64
+ emitEvent(sink, event);
65
+ return event;
66
+ },
67
+ });
68
+ },
69
+ beginTool() {
70
+ const startedAt = safeNow(clock);
71
+ let finished = false;
72
+ return Object.freeze({
73
+ finish(record) {
74
+ if (finished)
75
+ return undefined;
76
+ finished = true;
77
+ const endedAt = safeNow(clock, startedAt);
78
+ let event;
79
+ try {
80
+ event = createToolEvent(record, endedAt, boundedLatency(startedAt, endedAt));
81
+ }
82
+ catch {
83
+ return undefined;
84
+ }
85
+ emitEvent(sink, event);
86
+ return event;
87
+ },
88
+ });
89
+ },
90
+ });
91
+ }
92
+ /** A small JSON-lines adapter; only structured events can enter this port. */
93
+ function createJsonLinesEventSink(writeLine) {
94
+ if (typeof writeLine !== "function") {
95
+ throw new TypeError("JSON-lines destination must be a function");
96
+ }
97
+ return Object.freeze({
98
+ write(event) {
99
+ if (!ISSUED_STRUCTURED_EVENTS.has(event))
100
+ return;
101
+ suppressUnexpectedThenable(writeLine(`${JSON.stringify(event)}\n`));
102
+ },
103
+ });
104
+ }
105
+ /**
106
+ * Drop-aware nonblocking JSONL sink for streams such as stderr. Node already
107
+ * owns the line whose write returned false; later lines are retained only up
108
+ * to a fixed bound and excess volume is coalesced into one count record.
109
+ */
110
+ function createBoundedJsonLinesEventSink(options) {
111
+ if (!options ||
112
+ typeof options !== "object" ||
113
+ typeof options.writeLine !== "function" ||
114
+ typeof options.onDrain !== "function") {
115
+ throw new TypeError("bounded JSON-lines sink options are invalid");
116
+ }
117
+ const maximum = options.maxPendingLines ?? 256;
118
+ if (!Number.isSafeInteger(maximum) || maximum < 0 || maximum > 100_000) {
119
+ throw new TypeError("bounded JSON-lines pending limit is invalid");
120
+ }
121
+ const pending = [];
122
+ let dropped = 0;
123
+ let blocked = false;
124
+ let waitingForDrain = false;
125
+ const waitForDrain = () => {
126
+ if (waitingForDrain)
127
+ return;
128
+ waitingForDrain = true;
129
+ options.onDrain(() => {
130
+ waitingForDrain = false;
131
+ blocked = false;
132
+ flush();
133
+ });
134
+ };
135
+ const write = (line) => {
136
+ try {
137
+ if (!options.writeLine(line)) {
138
+ blocked = true;
139
+ waitForDrain();
140
+ }
141
+ }
142
+ catch {
143
+ blocked = true;
144
+ waitForDrain();
145
+ }
146
+ };
147
+ const flush = () => {
148
+ if (blocked)
149
+ return;
150
+ if (dropped > 0) {
151
+ const count = dropped;
152
+ dropped = 0;
153
+ write(`${JSON.stringify({ type: "telemetry_dropped", count })}\n`);
154
+ }
155
+ while (!blocked && pending.length > 0)
156
+ write(pending.shift());
157
+ };
158
+ return Object.freeze({
159
+ write(event) {
160
+ if (!ISSUED_STRUCTURED_EVENTS.has(event))
161
+ return;
162
+ const line = `${JSON.stringify(event)}\n`;
163
+ if (!blocked) {
164
+ write(line);
165
+ }
166
+ else if (pending.length < maximum) {
167
+ pending.push(line);
168
+ }
169
+ else {
170
+ dropped++;
171
+ }
172
+ },
173
+ });
174
+ }
175
+ /** Independent, bounded token buckets for pre-auth sources and identities. */
176
+ function createHttpRateLimiter(options) {
177
+ if (!options || typeof options !== "object") {
178
+ throw new TypeError("HTTP rate limiter options must be an object");
179
+ }
180
+ const clock = options.clock ?? SYSTEM_CLOCK;
181
+ if (!clock || typeof clock.now !== "function") {
182
+ throw new TypeError("HTTP rate limiter clock must implement now");
183
+ }
184
+ const preAuthentication = new BoundedTokenBucketLimiter("pre_auth_source", options.preAuthentication, clock);
185
+ const authenticatedIdentity = new BoundedTokenBucketLimiter("authenticated_identity", options.authenticatedIdentity, clock);
186
+ return Object.freeze({
187
+ checkPreAuthentication(sourceKey) {
188
+ const key = digestSourceKey(sourceKey);
189
+ return key
190
+ ? preAuthentication.check(key)
191
+ : preAuthentication.rejectInvalidKey();
192
+ },
193
+ checkAuthenticated(identity) {
194
+ const key = digestIdentityKey(identity);
195
+ return key
196
+ ? authenticatedIdentity.check(key)
197
+ : authenticatedIdentity.rejectInvalidKey();
198
+ },
199
+ });
200
+ }
201
+ /** Convert only an issued rejection into a generic HTTP 429 response. */
202
+ function safeHttpRateLimitRejection(decision) {
203
+ let retryAfterSeconds = 1;
204
+ try {
205
+ if (ISSUED_RATE_LIMIT_DECISIONS.has(decision) &&
206
+ decision.allowed === false) {
207
+ retryAfterSeconds = boundedRetryAfter(decision.retryAfterSeconds);
208
+ }
209
+ }
210
+ catch {
211
+ // Forged/hostile decisions receive the same generic minimum delay.
212
+ }
213
+ return Object.freeze({
214
+ status: 429,
215
+ headers: Object.freeze({
216
+ "cache-control": "no-store",
217
+ "content-type": "application/json; charset=utf-8",
218
+ "retry-after": String(retryAfterSeconds),
219
+ }),
220
+ body: `${JSON.stringify({
221
+ error: "rate_limited",
222
+ message: "Rate limited. Retry after the number of seconds in retry_after_seconds or the Retry-After header.",
223
+ retry_after_seconds: retryAfterSeconds,
224
+ })}
225
+ `,
226
+ });
227
+ }
228
+ class BoundedTokenBucketLimiter {
229
+ #scope;
230
+ #policy;
231
+ #clock;
232
+ #entries = new Map();
233
+ #lastNow = 0;
234
+ #nextPruneAt = Number.POSITIVE_INFINITY;
235
+ constructor(scope, policy, clock) {
236
+ this.#scope = scope;
237
+ this.#policy = immutableRateLimitPolicy(policy);
238
+ this.#clock = clock;
239
+ }
240
+ check(digestedKey) {
241
+ const now = this.#readNow();
242
+ if (now === undefined)
243
+ return this.#reject("clock_unavailable", 1);
244
+ let state = this.#entries.get(digestedKey);
245
+ if (!state) {
246
+ if (this.#entries.size >= this.#policy.maxEntries &&
247
+ now >= this.#nextPruneAt) {
248
+ this.#pruneFullAndSchedule(now);
249
+ }
250
+ if (this.#entries.size >= this.#policy.maxEntries) {
251
+ return this.#reject("key_capacity_exhausted", millisecondsToRetrySeconds(this.#nextPruneAt - now));
252
+ }
253
+ state = { tokens: this.#policy.capacity, updatedAt: now };
254
+ this.#entries.set(digestedKey, state);
255
+ }
256
+ else {
257
+ this.#refill(state, now);
258
+ }
259
+ if (state.tokens >= 1) {
260
+ state.tokens -= 1;
261
+ this.#scheduleFullState(state);
262
+ return issuedRateLimitDecision({
263
+ allowed: true,
264
+ scope: this.#scope,
265
+ limit: this.#policy.capacity,
266
+ remaining: Math.max(0, Math.floor(state.tokens)),
267
+ reason: null,
268
+ retryAfterSeconds: null,
269
+ });
270
+ }
271
+ const millisecondsPerToken = this.#policy.refillPeriodMs / this.#policy.capacity;
272
+ const waitMs = (1 - state.tokens) * millisecondsPerToken;
273
+ this.#scheduleFullState(state);
274
+ return this.#reject("rate_limited", millisecondsToRetrySeconds(waitMs));
275
+ }
276
+ rejectInvalidKey() {
277
+ return this.#reject("invalid_key", 1);
278
+ }
279
+ #readNow() {
280
+ let candidate;
281
+ try {
282
+ candidate = this.#clock.now();
283
+ }
284
+ catch {
285
+ return undefined;
286
+ }
287
+ if (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0) {
288
+ return undefined;
289
+ }
290
+ const monotonic = Math.max(this.#lastNow, candidate);
291
+ this.#lastNow = monotonic;
292
+ return monotonic;
293
+ }
294
+ #refill(state, now) {
295
+ const elapsed = Math.max(0, now - state.updatedAt);
296
+ state.tokens = Math.min(this.#policy.capacity, state.tokens +
297
+ (elapsed * this.#policy.capacity) / this.#policy.refillPeriodMs);
298
+ state.updatedAt = now;
299
+ }
300
+ /**
301
+ * Full-map cleanup is scheduled at the earliest possible full refill.
302
+ * New-key floods before that instant remain O(1) instead of scanning every
303
+ * retained entry on every rejected attempt.
304
+ */
305
+ #pruneFullAndSchedule(now) {
306
+ this.#nextPruneAt = Number.POSITIVE_INFINITY;
307
+ for (const [key, state] of this.#entries) {
308
+ const available = state.tokens +
309
+ (Math.max(0, now - state.updatedAt) * this.#policy.capacity) /
310
+ this.#policy.refillPeriodMs;
311
+ if (available >= this.#policy.capacity) {
312
+ this.#entries.delete(key);
313
+ }
314
+ else {
315
+ const missingTokens = this.#policy.capacity - available;
316
+ const fullAt = now +
317
+ (missingTokens * this.#policy.refillPeriodMs) /
318
+ this.#policy.capacity;
319
+ this.#nextPruneAt = Math.min(this.#nextPruneAt, fullAt);
320
+ }
321
+ }
322
+ }
323
+ #scheduleFullState(state) {
324
+ const missingTokens = Math.max(0, this.#policy.capacity - state.tokens);
325
+ const fullAt = state.updatedAt +
326
+ (missingTokens * this.#policy.refillPeriodMs) / this.#policy.capacity;
327
+ this.#nextPruneAt = Math.min(this.#nextPruneAt, fullAt);
328
+ }
329
+ #reject(reason, retryAfterSeconds) {
330
+ return issuedRateLimitDecision({
331
+ allowed: false,
332
+ scope: this.#scope,
333
+ limit: this.#policy.capacity,
334
+ remaining: 0,
335
+ reason,
336
+ retryAfterSeconds: boundedRetryAfter(retryAfterSeconds),
337
+ });
338
+ }
339
+ }
340
+ const SYSTEM_CLOCK = Object.freeze({
341
+ now: () => Date.now(),
342
+ });
343
+ function createRequestEvent(completion, observedAtMs, latencyMs) {
344
+ if (typeof completion !== "object" || completion === null) {
345
+ throw new TypeError("request completion must be an object");
346
+ }
347
+ const outcome = Reflect.get(completion, "outcome");
348
+ const reason = Reflect.get(completion, "reason");
349
+ const statusCode = Reflect.get(completion, "statusCode");
350
+ const correlationCandidate = Reflect.get(completion, "correlationId");
351
+ const identityCandidate = Reflect.get(completion, "identity");
352
+ if (outcome !== "success" &&
353
+ outcome !== "rejected" &&
354
+ outcome !== "error") {
355
+ throw new TypeError("request outcome is invalid");
356
+ }
357
+ if ((outcome === "success" && reason !== null) ||
358
+ (outcome !== "success" && !isHttpRequestReason(reason))) {
359
+ throw new TypeError("request outcome and reason are inconsistent");
360
+ }
361
+ if (typeof statusCode !== "number" ||
362
+ !Number.isInteger(statusCode) ||
363
+ statusCode < 100 ||
364
+ statusCode > 599) {
365
+ throw new TypeError("request status is invalid");
366
+ }
367
+ if ((outcome === "success" && statusCode >= 400) ||
368
+ (outcome === "rejected" &&
369
+ statusCode < 400 &&
370
+ reason !== "tool_input_rejected") ||
371
+ (outcome === "error" && statusCode < 500)) {
372
+ throw new TypeError("request outcome and status are inconsistent");
373
+ }
374
+ const identity = optionalIdentityHashes(identityCandidate);
375
+ return issuedStructuredEvent({
376
+ schemaVersion: EVENT_SCHEMA_VERSION,
377
+ type: "http_request",
378
+ observedAtMs,
379
+ latencyMs,
380
+ correlationId: optionalCorrelationId(correlationCandidate),
381
+ ownerIdHash: identity?.ownerIdHash ?? null,
382
+ clientIdHash: identity?.clientIdHash ?? null,
383
+ outcome,
384
+ reason,
385
+ statusCode,
386
+ });
387
+ }
388
+ function createToolEvent(record, observedAtMs, latencyMs) {
389
+ if (typeof record !== "object" || record === null) {
390
+ throw new TypeError("tool audit record must be an object");
391
+ }
392
+ const scope = Reflect.get(record, "scope");
393
+ const outcome = Reflect.get(record, "outcome");
394
+ const reason = Reflect.get(record, "reason");
395
+ const tool = safeToolName(Reflect.get(record, "tool"));
396
+ const correlationId = requiredCorrelationId(Reflect.get(record, "correlationId"));
397
+ const identity = requiredIdentityHashes(Reflect.get(record, "identity"));
398
+ let profile;
399
+ let instance;
400
+ let errorCategory = null;
401
+ let retry = null;
402
+ let retryAfterSeconds = null;
403
+ if (scope === "pre_context") {
404
+ const validPreContextDisposition = (outcome === "context_rejected" &&
405
+ (reason === "request_metadata_unavailable" ||
406
+ reason === "input_validation_failed")) ||
407
+ (outcome === "cancelled" &&
408
+ (reason === "request_cancelled" ||
409
+ reason === "request_deadline_exceeded"));
410
+ if (!validPreContextDisposition) {
411
+ throw new TypeError("pre-context audit disposition is invalid");
412
+ }
413
+ profile = null;
414
+ instance = null;
415
+ }
416
+ else {
417
+ const profileCandidate = Reflect.get(record, "profile");
418
+ const instanceCandidate = Reflect.get(record, "instance");
419
+ validateToolDisposition(outcome, reason, profileCandidate, instanceCandidate);
420
+ profile =
421
+ profileCandidate === null ? null : safeConfiguredLabel(profileCandidate);
422
+ instance =
423
+ instanceCandidate === null ? null : safeCanonicalOrigin(instanceCandidate);
424
+ if (outcome === "client_rejected" || outcome === "handler_error") {
425
+ errorCategory = safeToolErrorCategory(Reflect.get(record, "errorCategory"));
426
+ retry = safeToolErrorRetry(Reflect.get(record, "retry"));
427
+ retryAfterSeconds = safeToolRetryAfter(Reflect.get(record, "retryAfterSeconds"), retry);
428
+ }
429
+ }
430
+ return issuedStructuredEvent({
431
+ schemaVersion: EVENT_SCHEMA_VERSION,
432
+ type: "mcp_tool",
433
+ observedAtMs,
434
+ latencyMs,
435
+ correlationId,
436
+ ownerIdHash: identity.ownerIdHash,
437
+ clientIdHash: identity.clientIdHash,
438
+ tool,
439
+ profile,
440
+ instance,
441
+ outcome,
442
+ reason,
443
+ errorCategory,
444
+ retry,
445
+ retryAfterSeconds,
446
+ });
447
+ }
448
+ function safeToolErrorCategory(value) {
449
+ if (value !== "authentication" &&
450
+ value !== "authorization" &&
451
+ value !== "not_found" &&
452
+ value !== "conflict" &&
453
+ value !== "rate_limit" &&
454
+ value !== "timeout" &&
455
+ value !== "upstream" &&
456
+ value !== "internal") {
457
+ throw new TypeError("tool error category is invalid");
458
+ }
459
+ return value;
460
+ }
461
+ function safeToolErrorRetry(value) {
462
+ if (value !== "do_not_retry" &&
463
+ value !== "retry_after_correction" &&
464
+ value !== "retry_if_safe_and_idempotent" &&
465
+ value !== "retry_later") {
466
+ throw new TypeError("tool error retry decision is invalid");
467
+ }
468
+ return value;
469
+ }
470
+ function safeToolRetryAfter(value, retry) {
471
+ if (value === null)
472
+ return null;
473
+ if (retry !== "retry_later" ||
474
+ typeof value !== "number" ||
475
+ !Number.isSafeInteger(value) ||
476
+ value < 1 ||
477
+ value > tool_error_js_1.MAX_TOOL_ERROR_RETRY_AFTER_SECONDS) {
478
+ throw new TypeError("tool error retry-after is invalid");
479
+ }
480
+ return value;
481
+ }
482
+ function validateToolDisposition(outcome, reason, profile, instance) {
483
+ const unresolved = profile === null && instance === null;
484
+ const resolved = typeof profile === "string" && typeof instance === "string";
485
+ const valid = (outcome === "success" && reason === null && resolved) ||
486
+ (outcome === "profile_rejected" &&
487
+ (reason === "missing_profile" ||
488
+ reason === "unknown_profile" ||
489
+ reason === "invalid_profile") &&
490
+ unresolved) ||
491
+ (outcome === "context_rejected" &&
492
+ reason === "policy_context_unavailable" &&
493
+ resolved) ||
494
+ (outcome === "policy_rejected" &&
495
+ // Every policy-rejection reason the dispatcher can emit is valid here.
496
+ // Listing only the table denial silently rejected the sibling reasons
497
+ // and threw while building the structured event for them.
498
+ (reason === "table_access_denied" ||
499
+ reason === "field_access_denied" ||
500
+ reason === "encoded_query_denied" ||
501
+ reason === "structured_query_denied" ||
502
+ reason === "journal_update_denied" ||
503
+ reason === "write_value_denied") &&
504
+ resolved) ||
505
+ (outcome === "client_rejected" &&
506
+ (reason === "client_initialization_failed" ||
507
+ reason === "profile_binding_changed") &&
508
+ resolved) ||
509
+ (outcome === "cancelled" &&
510
+ (reason === "request_cancelled" ||
511
+ reason === "request_deadline_exceeded") &&
512
+ resolved) ||
513
+ (outcome === "handler_error" &&
514
+ (reason === "handler_threw" || reason === "handler_returned_error") &&
515
+ resolved);
516
+ if (!valid)
517
+ throw new TypeError("tool audit disposition is invalid");
518
+ }
519
+ function optionalIdentityHashes(value) {
520
+ return value === undefined ? undefined : requiredIdentityHashes(value);
521
+ }
522
+ function requiredIdentityHashes(value) {
523
+ if (typeof value !== "object" || value === null) {
524
+ throw new TypeError("identity is invalid");
525
+ }
526
+ const ownerId = safeRateLimitKeyPart(Reflect.get(value, "ownerId"));
527
+ const clientId = safeRateLimitKeyPart(Reflect.get(value, "clientId"));
528
+ return Object.freeze({
529
+ ownerIdHash: digestParts("owner", [ownerId]),
530
+ clientIdHash: digestParts("client", [clientId]),
531
+ });
532
+ }
533
+ function optionalCorrelationId(value) {
534
+ return value === undefined ? null : requiredCorrelationId(value);
535
+ }
536
+ function requiredCorrelationId(value) {
537
+ return safeBoundedString(value, "correlation ID", MAX_LABEL_LENGTH);
538
+ }
539
+ function safeToolName(value) {
540
+ const tool = safeBoundedString(value, "tool name", MAX_LABEL_LENGTH);
541
+ if (!SAFE_TOOL_NAME.test(tool))
542
+ throw new TypeError("tool name is invalid");
543
+ return tool;
544
+ }
545
+ function safeConfiguredLabel(value) {
546
+ return safeBoundedString(value, "configured label", MAX_LABEL_LENGTH);
547
+ }
548
+ function safeCanonicalOrigin(value) {
549
+ const candidate = safeBoundedString(value, "instance", MAX_ORIGIN_LENGTH);
550
+ const parsed = new URL(candidate);
551
+ if (parsed.protocol !== "https:" ||
552
+ parsed.username ||
553
+ parsed.password ||
554
+ parsed.search ||
555
+ parsed.hash ||
556
+ (parsed.pathname !== "" && parsed.pathname !== "/")) {
557
+ throw new TypeError("instance must be a canonical HTTPS origin");
558
+ }
559
+ return parsed.origin;
560
+ }
561
+ function safeBoundedString(value, label, maximum) {
562
+ if (typeof value !== "string")
563
+ throw new TypeError(`${label} must be a string`);
564
+ const normalized = value.trim();
565
+ if (normalized.length === 0 ||
566
+ normalized.length > maximum ||
567
+ UNSAFE_LOG_CHARACTER.test(normalized)) {
568
+ throw new TypeError(`${label} is invalid`);
569
+ }
570
+ return normalized;
571
+ }
572
+ function digestSourceKey(value) {
573
+ try {
574
+ return digestParts("pre-auth", [safeRateLimitKeyPart(value)]);
575
+ }
576
+ catch {
577
+ return undefined;
578
+ }
579
+ }
580
+ function digestIdentityKey(value) {
581
+ try {
582
+ if (typeof value !== "object" || value === null)
583
+ return undefined;
584
+ const ownerId = safeRateLimitKeyPart(Reflect.get(value, "ownerId"));
585
+ const clientId = safeRateLimitKeyPart(Reflect.get(value, "clientId"));
586
+ return digestParts("authenticated", [ownerId, clientId]);
587
+ }
588
+ catch {
589
+ return undefined;
590
+ }
591
+ }
592
+ function safeRateLimitKeyPart(value) {
593
+ if (typeof value !== "string")
594
+ throw new TypeError("rate-limit key is invalid");
595
+ // Raw key material is hashed immediately and is never emitted, so accepting
596
+ // the full bounded string domain avoids narrowing the authentication
597
+ // identity contract merely because an identifier contains Unicode format
598
+ // characters. Empty and oversized values still fail closed.
599
+ if (value.length === 0 || value.length > MAX_RATE_LIMIT_KEY_LENGTH) {
600
+ throw new TypeError("rate-limit key is invalid");
601
+ }
602
+ return value;
603
+ }
604
+ /** Length-prefix every part so different owner/client splits cannot collide. */
605
+ function digestParts(namespace, parts) {
606
+ const hash = (0, node_crypto_1.createHash)("sha256").update(`${namespace}\0`, "utf8");
607
+ for (const part of parts) {
608
+ const bytes = Buffer.from(part, "utf8");
609
+ hash.update(String(bytes.length), "ascii").update(":", "ascii").update(bytes);
610
+ }
611
+ return `sha256:${hash.digest("hex")}`;
612
+ }
613
+ function immutableRateLimitPolicy(policy) {
614
+ if (typeof policy !== "object" || policy === null) {
615
+ throw new TypeError("rate-limit policy must be an object");
616
+ }
617
+ const capacity = Reflect.get(policy, "capacity");
618
+ const refillPeriodMs = Reflect.get(policy, "refillPeriodMs");
619
+ const maxEntries = Reflect.get(policy, "maxEntries");
620
+ if (typeof capacity !== "number" ||
621
+ !Number.isSafeInteger(capacity) ||
622
+ capacity < 1 ||
623
+ capacity > exports.MAX_RATE_LIMIT_CAPACITY) {
624
+ throw new TypeError("rate-limit capacity is invalid");
625
+ }
626
+ if (typeof refillPeriodMs !== "number" ||
627
+ !Number.isSafeInteger(refillPeriodMs) ||
628
+ refillPeriodMs < 1 ||
629
+ refillPeriodMs > exports.MAX_RATE_LIMIT_PERIOD_MS) {
630
+ throw new TypeError("rate-limit refillPeriodMs is invalid");
631
+ }
632
+ if (typeof maxEntries !== "number" ||
633
+ !Number.isSafeInteger(maxEntries) ||
634
+ maxEntries < 1 ||
635
+ maxEntries > exports.MAX_RATE_LIMIT_ENTRIES) {
636
+ throw new TypeError("rate-limit maxEntries is invalid");
637
+ }
638
+ return Object.freeze({ capacity, refillPeriodMs, maxEntries });
639
+ }
640
+ function issuedRateLimitDecision(decision) {
641
+ const issued = Object.freeze(decision);
642
+ ISSUED_RATE_LIMIT_DECISIONS.add(issued);
643
+ return issued;
644
+ }
645
+ function issuedStructuredEvent(event) {
646
+ const issued = Object.freeze(event);
647
+ ISSUED_STRUCTURED_EVENTS.add(issued);
648
+ return issued;
649
+ }
650
+ function emitEvent(sink, event) {
651
+ try {
652
+ suppressUnexpectedThenable(sink.write(event));
653
+ }
654
+ catch {
655
+ // Observability must not alter request/tool behavior.
656
+ }
657
+ }
658
+ function suppressUnexpectedThenable(value) {
659
+ if (((typeof value === "object" && value !== null) ||
660
+ typeof value === "function") &&
661
+ safeThen(value)) {
662
+ void Promise.resolve(value).catch(() => { });
663
+ }
664
+ }
665
+ function safeThen(value) {
666
+ try {
667
+ return typeof Reflect.get(value, "then") === "function";
668
+ }
669
+ catch {
670
+ return false;
671
+ }
672
+ }
673
+ function safeNow(clock, fallback = 0) {
674
+ try {
675
+ const value = clock.now();
676
+ return typeof value === "number" && Number.isFinite(value) && value >= 0
677
+ ? Math.max(fallback, value)
678
+ : fallback;
679
+ }
680
+ catch {
681
+ return fallback;
682
+ }
683
+ }
684
+ function boundedLatency(startedAt, endedAt) {
685
+ return Math.min(MAX_LATENCY_MS, Math.max(0, Math.round(endedAt - startedAt)));
686
+ }
687
+ function isHttpRequestReason(value) {
688
+ return (value === "not_found" ||
689
+ value === "method_not_allowed" ||
690
+ value === "unauthorized" ||
691
+ value === "forbidden" ||
692
+ value === "pre_auth_rate_limited" ||
693
+ value === "identity_rate_limited" ||
694
+ value === "invalid_content_type" ||
695
+ value === "invalid_protocol" ||
696
+ value === "malformed_request" ||
697
+ value === "request_too_large" ||
698
+ value === "request_timeout" ||
699
+ value === "client_disconnected" ||
700
+ value === "concurrency_limited" ||
701
+ value === "tool_input_rejected" ||
702
+ value === "service_unavailable" ||
703
+ value === "internal_error");
704
+ }
705
+ function millisecondsToRetrySeconds(milliseconds) {
706
+ return boundedRetryAfter(Math.ceil(Math.max(0, milliseconds) / 1_000));
707
+ }
708
+ function boundedRetryAfter(value) {
709
+ return Math.min(86_400, Math.max(1, Math.ceil(value)));
710
+ }
711
+ //# sourceMappingURL=http-observability.js.map