@onlyflows/servicenow-mcp 1.0.0 → 2.0.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 +153 -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 +439 -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 +703 -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/incident-write-policy.d.ts +20 -0
  57. package/dist/incident-write-policy.d.ts.map +1 -0
  58. package/dist/incident-write-policy.js +196 -0
  59. package/dist/incident-write-policy.js.map +1 -0
  60. package/dist/index.d.ts +14 -4
  61. package/dist/index.d.ts.map +1 -1
  62. package/dist/index.js +140 -36
  63. package/dist/index.js.map +1 -1
  64. package/dist/metadata-cache.d.ts +71 -0
  65. package/dist/metadata-cache.d.ts.map +1 -0
  66. package/dist/metadata-cache.js +397 -0
  67. package/dist/metadata-cache.js.map +1 -0
  68. package/dist/profile-admin.d.ts +64 -0
  69. package/dist/profile-admin.d.ts.map +1 -0
  70. package/dist/profile-admin.js +351 -0
  71. package/dist/profile-admin.js.map +1 -0
  72. package/dist/profile-credentials.d.ts +68 -0
  73. package/dist/profile-credentials.d.ts.map +1 -0
  74. package/dist/profile-credentials.js +329 -0
  75. package/dist/profile-credentials.js.map +1 -0
  76. package/dist/profile-manager.d.ts +187 -0
  77. package/dist/profile-manager.d.ts.map +1 -0
  78. package/dist/profile-manager.js +1026 -0
  79. package/dist/profile-manager.js.map +1 -0
  80. package/dist/record-identifier-policy.d.ts +39 -0
  81. package/dist/record-identifier-policy.d.ts.map +1 -0
  82. package/dist/record-identifier-policy.js +203 -0
  83. package/dist/record-identifier-policy.js.map +1 -0
  84. package/dist/runtime-environment.d.ts +23 -0
  85. package/dist/runtime-environment.d.ts.map +1 -0
  86. package/dist/runtime-environment.js +58 -0
  87. package/dist/runtime-environment.js.map +1 -0
  88. package/dist/server.d.ts +33 -0
  89. package/dist/server.d.ts.map +1 -0
  90. package/dist/server.js +73 -0
  91. package/dist/server.js.map +1 -0
  92. package/dist/servicenow-identifiers.d.ts +8 -0
  93. package/dist/servicenow-identifiers.d.ts.map +1 -0
  94. package/dist/servicenow-identifiers.js +22 -0
  95. package/dist/servicenow-identifiers.js.map +1 -0
  96. package/dist/setup-prompts.d.ts +7 -0
  97. package/dist/setup-prompts.d.ts.map +1 -0
  98. package/dist/setup-prompts.js +123 -0
  99. package/dist/setup-prompts.js.map +1 -0
  100. package/dist/setup.d.ts +109 -0
  101. package/dist/setup.d.ts.map +1 -0
  102. package/dist/setup.js +1903 -0
  103. package/dist/setup.js.map +1 -0
  104. package/dist/startup.d.ts +43 -0
  105. package/dist/startup.d.ts.map +1 -0
  106. package/dist/startup.js +75 -0
  107. package/dist/startup.js.map +1 -0
  108. package/dist/stdio-runtime.d.ts +106 -0
  109. package/dist/stdio-runtime.d.ts.map +1 -0
  110. package/dist/stdio-runtime.js +231 -0
  111. package/dist/stdio-runtime.js.map +1 -0
  112. package/dist/structured-query.d.ts +187 -0
  113. package/dist/structured-query.d.ts.map +1 -0
  114. package/dist/structured-query.js +503 -0
  115. package/dist/structured-query.js.map +1 -0
  116. package/dist/table-defaults.d.ts +28 -0
  117. package/dist/table-defaults.d.ts.map +1 -0
  118. package/dist/table-defaults.js +85 -0
  119. package/dist/table-defaults.js.map +1 -0
  120. package/dist/table-policy.d.ts +71 -0
  121. package/dist/table-policy.d.ts.map +1 -0
  122. package/dist/table-policy.js +290 -0
  123. package/dist/table-policy.js.map +1 -0
  124. package/dist/tool-error.d.ts +48 -0
  125. package/dist/tool-error.d.ts.map +1 -0
  126. package/dist/tool-error.js +139 -0
  127. package/dist/tool-error.js.map +1 -0
  128. package/dist/tool-table-access.d.ts +19 -0
  129. package/dist/tool-table-access.d.ts.map +1 -0
  130. package/dist/tool-table-access.js +388 -0
  131. package/dist/tool-table-access.js.map +1 -0
  132. package/dist/tools/aggregate.d.ts +22 -42
  133. package/dist/tools/aggregate.d.ts.map +1 -1
  134. package/dist/tools/aggregate.js +103 -47
  135. package/dist/tools/aggregate.js.map +1 -1
  136. package/dist/tools/all-fields-cap.d.ts +45 -0
  137. package/dist/tools/all-fields-cap.d.ts.map +1 -0
  138. package/dist/tools/all-fields-cap.js +151 -0
  139. package/dist/tools/all-fields-cap.js.map +1 -0
  140. package/dist/tools/atf.d.ts +21 -60
  141. package/dist/tools/atf.d.ts.map +1 -1
  142. package/dist/tools/atf.js +180 -116
  143. package/dist/tools/atf.js.map +1 -1
  144. package/dist/tools/attach.d.ts +31 -45
  145. package/dist/tools/attach.d.ts.map +1 -1
  146. package/dist/tools/attach.js +175 -137
  147. package/dist/tools/attach.js.map +1 -1
  148. package/dist/tools/batch.d.ts +78 -42
  149. package/dist/tools/batch.d.ts.map +1 -1
  150. package/dist/tools/batch.js +172 -68
  151. package/dist/tools/batch.js.map +1 -1
  152. package/dist/tools/catalog.d.ts +6 -0
  153. package/dist/tools/catalog.d.ts.map +1 -0
  154. package/dist/tools/catalog.js +203 -0
  155. package/dist/tools/catalog.js.map +1 -0
  156. package/dist/tools/codesearch.d.ts +14 -25
  157. package/dist/tools/codesearch.d.ts.map +1 -1
  158. package/dist/tools/codesearch.js +60 -48
  159. package/dist/tools/codesearch.js.map +1 -1
  160. package/dist/tools/create-module.d.ts +48 -0
  161. package/dist/tools/create-module.d.ts.map +1 -0
  162. package/dist/tools/create-module.js +94 -0
  163. package/dist/tools/create-module.js.map +1 -0
  164. package/dist/tools/create.d.ts +2 -38
  165. package/dist/tools/create.d.ts.map +1 -1
  166. package/dist/tools/create.js +9 -41
  167. package/dist/tools/create.js.map +1 -1
  168. package/dist/tools/delete.d.ts +13 -23
  169. package/dist/tools/delete.d.ts.map +1 -1
  170. package/dist/tools/delete.js +30 -33
  171. package/dist/tools/delete.js.map +1 -1
  172. package/dist/tools/discover.d.ts +15 -27
  173. package/dist/tools/discover.d.ts.map +1 -1
  174. package/dist/tools/discover.js +103 -60
  175. package/dist/tools/discover.js.map +1 -1
  176. package/dist/tools/get-module.d.ts +85 -0
  177. package/dist/tools/get-module.d.ts.map +1 -0
  178. package/dist/tools/get-module.js +221 -0
  179. package/dist/tools/get-module.js.map +1 -0
  180. package/dist/tools/get.d.ts +2 -51
  181. package/dist/tools/get.d.ts.map +1 -1
  182. package/dist/tools/get.js +9 -49
  183. package/dist/tools/get.js.map +1 -1
  184. package/dist/tools/handler-result.d.ts +14 -0
  185. package/dist/tools/handler-result.d.ts.map +1 -0
  186. package/dist/tools/handler-result.js +177 -0
  187. package/dist/tools/handler-result.js.map +1 -0
  188. package/dist/tools/health.d.ts +12 -15
  189. package/dist/tools/health.d.ts.map +1 -1
  190. package/dist/tools/health.js +55 -36
  191. package/dist/tools/health.js.map +1 -1
  192. package/dist/tools/incident-journal-module.d.ts +12 -0
  193. package/dist/tools/incident-journal-module.d.ts.map +1 -0
  194. package/dist/tools/incident-journal-module.js +61 -0
  195. package/dist/tools/incident-journal-module.js.map +1 -0
  196. package/dist/tools/incident-write-shared.d.ts +6 -0
  197. package/dist/tools/incident-write-shared.d.ts.map +1 -0
  198. package/dist/tools/incident-write-shared.js +64 -0
  199. package/dist/tools/incident-write-shared.js.map +1 -0
  200. package/dist/tools/index.d.ts +47 -36
  201. package/dist/tools/index.d.ts.map +1 -1
  202. package/dist/tools/index.js +795 -35
  203. package/dist/tools/index.js.map +1 -1
  204. package/dist/tools/nl.d.ts +10 -24
  205. package/dist/tools/nl.d.ts.map +1 -1
  206. package/dist/tools/nl.js +37 -147
  207. package/dist/tools/nl.js.map +1 -1
  208. package/dist/tools/profile.d.ts +37 -0
  209. package/dist/tools/profile.d.ts.map +1 -0
  210. package/dist/tools/profile.js +39 -0
  211. package/dist/tools/profile.js.map +1 -0
  212. package/dist/tools/query-module.d.ts +119 -0
  213. package/dist/tools/query-module.d.ts.map +1 -0
  214. package/dist/tools/query-module.js +324 -0
  215. package/dist/tools/query-module.js.map +1 -0
  216. package/dist/tools/query.d.ts +2 -72
  217. package/dist/tools/query.d.ts.map +1 -1
  218. package/dist/tools/query.js +8 -72
  219. package/dist/tools/query.js.map +1 -1
  220. package/dist/tools/relationships.d.ts +21 -42
  221. package/dist/tools/relationships.d.ts.map +1 -1
  222. package/dist/tools/relationships.js +70 -56
  223. package/dist/tools/relationships.js.map +1 -1
  224. package/dist/tools/result-envelope.d.ts +603 -0
  225. package/dist/tools/result-envelope.d.ts.map +1 -0
  226. package/dist/tools/result-envelope.js +767 -0
  227. package/dist/tools/result-envelope.js.map +1 -0
  228. package/dist/tools/schema-module.d.ts +64 -0
  229. package/dist/tools/schema-module.d.ts.map +1 -0
  230. package/dist/tools/schema-module.js +367 -0
  231. package/dist/tools/schema-module.js.map +1 -0
  232. package/dist/tools/schema.d.ts +2 -37
  233. package/dist/tools/schema.d.ts.map +1 -1
  234. package/dist/tools/schema.js +6 -57
  235. package/dist/tools/schema.js.map +1 -1
  236. package/dist/tools/script.d.ts +33 -27
  237. package/dist/tools/script.d.ts.map +1 -1
  238. package/dist/tools/script.js +43 -37
  239. package/dist/tools/script.js.map +1 -1
  240. package/dist/tools/syslog.d.ts +19 -46
  241. package/dist/tools/syslog.d.ts.map +1 -1
  242. package/dist/tools/syslog.js +101 -67
  243. package/dist/tools/syslog.js.map +1 -1
  244. package/dist/tools/tool-module.d.ts +143 -0
  245. package/dist/tools/tool-module.d.ts.map +1 -0
  246. package/dist/tools/tool-module.js +1095 -0
  247. package/dist/tools/tool-module.js.map +1 -0
  248. package/dist/tools/update-module.d.ts +51 -0
  249. package/dist/tools/update-module.d.ts.map +1 -0
  250. package/dist/tools/update-module.js +107 -0
  251. package/dist/tools/update-module.js.map +1 -0
  252. package/dist/tools/update.d.ts +2 -45
  253. package/dist/tools/update.d.ts.map +1 -1
  254. package/dist/tools/update.js +9 -41
  255. package/dist/tools/update.js.map +1 -1
  256. package/dist/utils.d.ts +68 -1
  257. package/dist/utils.d.ts.map +1 -1
  258. package/dist/utils.js +114 -16
  259. package/dist/utils.js.map +1 -1
  260. package/dist/version.d.ts +10 -0
  261. package/dist/version.d.ts.map +1 -0
  262. package/dist/version.js +13 -0
  263. package/dist/version.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,1321 @@
1
+ "use strict";
2
+ /**
3
+ * Provider-neutral Node.js Streamable HTTP runtime.
4
+ *
5
+ * Statelessness is enforced by constructing a fresh MCP server and official
6
+ * SDK transport for every accepted POST. Authentication happens before the
7
+ * body is parsed or the injected server factory is called.
8
+ *
9
+ * @module http-runtime
10
+ */
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.MAX_ESTIMATED_CONCURRENT_BODY_MEMORY_BYTES = exports.RAW_RESPONSE_MEMORY_SAFETY_FACTOR = exports.BODY_MEMORY_SAFETY_FACTOR = exports.REJECTED_BODY_DRAIN_TIMEOUT_MS = exports.MAX_REJECTED_BODY_DRAIN_BYTES = exports.MAX_HTTP_CONNECTIONS = exports.DEFAULT_MAX_HTTP_CONNECTIONS = exports.DEFAULT_MAX_CONCURRENT_MCP_REQUESTS = exports.DEFAULT_HTTP_CLOSE_GRACE_PERIOD_MS = exports.DEFAULT_MCP_HTTP_PORT = exports.DEFAULT_MCP_HTTP_HOST = exports.MCP_READINESS_PATH = exports.MCP_LIVENESS_PATH = exports.MCP_HTTP_PATH = void 0;
13
+ exports.createHttpRuntime = createHttpRuntime;
14
+ const node_crypto_1 = require("node:crypto");
15
+ const node_http_1 = require("node:http");
16
+ const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
17
+ const streamableHttp_js_1 = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
18
+ const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
19
+ const client_js_1 = require("./client.js");
20
+ const http_auth_js_1 = require("./http-auth.js");
21
+ const execution_context_js_1 = require("./execution-context.js");
22
+ const http_observability_js_1 = require("./http-observability.js");
23
+ const http_request_policy_js_1 = require("./http-request-policy.js");
24
+ const http_request_signal_js_1 = require("./http-request-signal.js");
25
+ exports.MCP_HTTP_PATH = "/mcp";
26
+ exports.MCP_LIVENESS_PATH = "/health/live";
27
+ exports.MCP_READINESS_PATH = "/health/ready";
28
+ exports.DEFAULT_MCP_HTTP_HOST = "127.0.0.1";
29
+ exports.DEFAULT_MCP_HTTP_PORT = 3000;
30
+ exports.DEFAULT_HTTP_CLOSE_GRACE_PERIOD_MS = 10_000;
31
+ exports.DEFAULT_MAX_CONCURRENT_MCP_REQUESTS = 2;
32
+ exports.DEFAULT_MAX_HTTP_CONNECTIONS = 128;
33
+ exports.MAX_HTTP_CONNECTIONS = 4_096;
34
+ exports.MAX_REJECTED_BODY_DRAIN_BYTES = 16 * 1024;
35
+ exports.REJECTED_BODY_DRAIN_TIMEOUT_MS = 100;
36
+ const MCP_SERVER_CLOSE_TIMEOUT_MS = 1_000;
37
+ const MAX_CONCURRENT_MCP_REQUESTS = 1_024;
38
+ /** Above the observed 22.4× heap / 54× RSS hostile JSON expansion. */
39
+ exports.BODY_MEMORY_SAFETY_FACTOR = 64;
40
+ exports.RAW_RESPONSE_MEMORY_SAFETY_FACTOR = 8;
41
+ exports.MAX_ESTIMATED_CONCURRENT_BODY_MEMORY_BYTES = 512 * 1024 * 1024;
42
+ const REQUEST_CORRELATION_HEADER = "x-request-id";
43
+ const JSON_ERROR_HEADERS = Object.freeze({
44
+ "cache-control": "no-store",
45
+ "content-type": "application/json; charset=utf-8",
46
+ });
47
+ const LIVE_BODY = '{"status":"live"}\n';
48
+ const READY_BODY = '{"status":"ready"}\n';
49
+ const NOT_READY_BODY = '{"status":"not_ready"}\n';
50
+ /** Create an inert runtime. No socket is opened until `start()` resolves. */
51
+ function createHttpRuntime(options) {
52
+ return new StatelessHttpRuntime(options);
53
+ }
54
+ class StatelessHttpRuntime {
55
+ #host;
56
+ #port;
57
+ #authenticationProvider;
58
+ #readinessCheck;
59
+ #observability;
60
+ #rateLimiter;
61
+ #requestPolicy;
62
+ #requestPolicyLimits;
63
+ #maxConcurrentRequests;
64
+ #maxConnections;
65
+ #createMcpServer;
66
+ #sockets = new Set();
67
+ #inFlight = new Set();
68
+ #activeMcpServers = new Set();
69
+ #activeRequestDeadlines = new Set();
70
+ #clientErrorSockets = new WeakSet();
71
+ #activeParserRequests = new WeakMap();
72
+ #admittedRequestCount = 0;
73
+ #state = "new";
74
+ #httpServer;
75
+ #startPromise;
76
+ #address;
77
+ #closePromise;
78
+ constructor(options) {
79
+ if (!options || typeof options !== "object") {
80
+ throw new TypeError("HTTP runtime options must be an object");
81
+ }
82
+ if (!options.authenticationProvider ||
83
+ typeof options.authenticationProvider.authenticate !== "function") {
84
+ throw new TypeError("HTTP authentication provider must implement authenticate");
85
+ }
86
+ if (typeof options.createServer !== "function") {
87
+ throw new TypeError("HTTP runtime createServer must be a function");
88
+ }
89
+ if (options.readinessCheck !== undefined &&
90
+ typeof options.readinessCheck !== "function") {
91
+ throw new TypeError("HTTP runtime readinessCheck must be a function");
92
+ }
93
+ if (options.observability !== undefined &&
94
+ (typeof options.observability !== "object" ||
95
+ typeof options.observability.beginRequest !== "function" ||
96
+ typeof options.observability.beginTool !== "function")) {
97
+ throw new TypeError("HTTP runtime observability is invalid");
98
+ }
99
+ if (options.rateLimiter !== undefined &&
100
+ (typeof options.rateLimiter !== "object" ||
101
+ typeof options.rateLimiter.checkPreAuthentication !== "function" ||
102
+ typeof options.rateLimiter.checkAuthenticated !== "function")) {
103
+ throw new TypeError("HTTP runtime rateLimiter is invalid");
104
+ }
105
+ this.#host = validateHost(options.host ?? exports.DEFAULT_MCP_HTTP_HOST);
106
+ this.#port = validatePort(options.port ?? exports.DEFAULT_MCP_HTTP_PORT);
107
+ this.#authenticationProvider = options.authenticationProvider;
108
+ this.#readinessCheck = options.readinessCheck;
109
+ this.#observability = options.observability;
110
+ this.#rateLimiter = options.rateLimiter;
111
+ this.#requestPolicy = options.requestPolicy ?? (0, http_request_policy_js_1.createHttpRequestPolicy)();
112
+ this.#requestPolicyLimits = (0, http_request_policy_js_1.httpRequestPolicyLimits)(this.#requestPolicy);
113
+ this.#maxConcurrentRequests = validateMaxConcurrentRequests(options.maxConcurrentRequests ?? exports.DEFAULT_MAX_CONCURRENT_MCP_REQUESTS);
114
+ this.#maxConnections = validateMaxConnections(options.maxConnections ?? exports.DEFAULT_MAX_HTTP_CONNECTIONS);
115
+ if (this.#maxConcurrentRequests *
116
+ ((this.#requestPolicyLimits.maxBodyBytes +
117
+ client_js_1.MAX_CUMULATIVE_UPSTREAM_JSON_BYTES) *
118
+ exports.BODY_MEMORY_SAFETY_FACTOR +
119
+ client_js_1.MAX_CUMULATIVE_RAW_RESPONSE_BYTES *
120
+ exports.RAW_RESPONSE_MEMORY_SAFETY_FACTOR) >
121
+ exports.MAX_ESTIMATED_CONCURRENT_BODY_MEMORY_BYTES) {
122
+ throw new TypeError("HTTP maxConcurrentRequests and maxBodyBytes exceed the estimated body-memory ceiling");
123
+ }
124
+ this.#createMcpServer = options.createServer;
125
+ }
126
+ start() {
127
+ if (this.#state === "closing" || this.#state === "closed") {
128
+ return Promise.reject(new Error("HTTP runtime cannot restart after close"));
129
+ }
130
+ if (this.#address)
131
+ return Promise.resolve(this.#address);
132
+ if (this.#startPromise)
133
+ return this.#startPromise;
134
+ this.#state = "starting";
135
+ const httpServer = (0, node_http_1.createServer)({
136
+ headersTimeout: this.#requestPolicyLimits.headersTimeoutMs,
137
+ requestTimeout: this.#requestPolicyLimits.requestTimeoutMs,
138
+ keepAliveTimeout: this.#requestPolicyLimits.keepAliveTimeoutMs,
139
+ connectionsCheckingInterval: Math.min(1_000, this.#requestPolicyLimits.headersTimeoutMs, this.#requestPolicyLimits.requestTimeoutMs),
140
+ }, (request, response) => {
141
+ const operation = this.#handleNodeRequest(request, response);
142
+ this.#inFlight.add(operation);
143
+ void operation.then(() => this.#inFlight.delete(operation), () => this.#inFlight.delete(operation));
144
+ });
145
+ httpServer.maxHeadersCount = 100;
146
+ httpServer.maxConnections = this.#maxConnections;
147
+ // Node 22+ uses this flag when a server participates in a cluster. Older
148
+ // supported runtimes safely ignore the own property, while the explicit
149
+ // connection listener below preserves the same fail-closed behavior.
150
+ httpServer.dropMaxConnection =
151
+ true;
152
+ this.#httpServer = httpServer;
153
+ httpServer.on("clientError", (error, socket) => {
154
+ this.#handleClientError(error, socket);
155
+ });
156
+ httpServer.on("connection", (socket) => {
157
+ if (this.#sockets.size >= this.#maxConnections) {
158
+ socket.destroy();
159
+ return;
160
+ }
161
+ this.#sockets.add(socket);
162
+ socket.once("close", () => {
163
+ this.#sockets.delete(socket);
164
+ this.#activeParserRequests.delete(socket);
165
+ });
166
+ });
167
+ this.#startPromise = new Promise((resolve, reject) => {
168
+ const onStartupError = (error) => {
169
+ this.#state = "closed";
170
+ reject(error);
171
+ };
172
+ httpServer.once("error", onStartupError);
173
+ httpServer.listen(this.#port, this.#host, () => {
174
+ httpServer.off("error", onStartupError);
175
+ const address = httpServer.address();
176
+ if (!address || typeof address === "string") {
177
+ this.#state = "closed";
178
+ void closeNodeServer(httpServer);
179
+ reject(new Error("HTTP runtime did not receive a TCP listen address"));
180
+ return;
181
+ }
182
+ const host = address.address;
183
+ const port = address.port;
184
+ const urlHost = host.includes(":") ? `[${host}]` : host;
185
+ this.#address = Object.freeze({
186
+ url: new URL(`http://${urlHost}:${port}${exports.MCP_HTTP_PATH}`),
187
+ host,
188
+ port,
189
+ });
190
+ // A concurrent close may already own the state. Resolving start lets
191
+ // that close proceed to stop the newly opened listener, while request
192
+ // admission remains disabled throughout the race.
193
+ if (this.#state === "starting")
194
+ this.#state = "listening";
195
+ resolve(this.#address);
196
+ });
197
+ });
198
+ return this.#startPromise;
199
+ }
200
+ isReady() {
201
+ if (this.#state !== "listening" || !this.#readinessCheck)
202
+ return false;
203
+ try {
204
+ const dependencyReady = this.#readinessCheck() === true;
205
+ return dependencyReady && this.#state === "listening";
206
+ }
207
+ catch {
208
+ return false;
209
+ }
210
+ }
211
+ close(options = {}) {
212
+ if (this.#closePromise)
213
+ return this.#closePromise;
214
+ const gracePeriodMs = validateGracePeriod(options.gracePeriodMs ?? exports.DEFAULT_HTTP_CLOSE_GRACE_PERIOD_MS);
215
+ this.#state = "closing";
216
+ this.#closePromise = this.#closeWithin(gracePeriodMs).finally(() => {
217
+ this.#state = "closed";
218
+ this.#address = undefined;
219
+ });
220
+ return this.#closePromise;
221
+ }
222
+ async #closeWithin(gracePeriodMs) {
223
+ if (this.#startPromise) {
224
+ try {
225
+ await this.#startPromise;
226
+ }
227
+ catch {
228
+ return;
229
+ }
230
+ }
231
+ const httpServer = this.#httpServer;
232
+ if (!httpServer)
233
+ return;
234
+ const listenerClosed = closeNodeServer(httpServer);
235
+ httpServer.closeIdleConnections?.();
236
+ const requestsDrained = this.#drainAcceptedRequests().then(() => {
237
+ // On Node 18, a connection that becomes idle after server.close() may
238
+ // otherwise remain open until its keep-alive timeout.
239
+ httpServer.closeIdleConnections?.();
240
+ });
241
+ const graceful = Promise.all([listenerClosed, requestsDrained]).then(() => undefined);
242
+ if (gracePeriodMs === 0) {
243
+ this.#forceClose(httpServer);
244
+ void listenerClosed.catch(() => { });
245
+ return;
246
+ }
247
+ let timer;
248
+ const deadline = new Promise((resolve) => {
249
+ timer = setTimeout(() => resolve("deadline"), gracePeriodMs);
250
+ timer.unref?.();
251
+ });
252
+ const outcome = await Promise.race([
253
+ graceful.then(() => "graceful"),
254
+ deadline,
255
+ ]);
256
+ if (timer)
257
+ clearTimeout(timer);
258
+ if (outcome === "deadline" || this.#activeMcpServers.size > 0) {
259
+ this.#forceClose(httpServer);
260
+ }
261
+ }
262
+ async #drainAcceptedRequests() {
263
+ while (this.#inFlight.size > 0) {
264
+ await Promise.allSettled([...this.#inFlight]);
265
+ }
266
+ }
267
+ #forceClose(httpServer) {
268
+ for (const deadline of this.#activeRequestDeadlines) {
269
+ deadline.cancel("shutdown");
270
+ }
271
+ for (const mcpServer of this.#activeMcpServers) {
272
+ try {
273
+ void Promise.resolve(mcpServer.close()).catch(() => { });
274
+ }
275
+ catch {
276
+ // A hostile or overridden close must not prevent socket destruction.
277
+ }
278
+ }
279
+ httpServer.closeAllConnections?.();
280
+ for (const socket of this.#sockets)
281
+ socket.destroy();
282
+ // A provider, application factory, tool handler, or SDK cleanup hook may
283
+ // ignore connection closure and never settle. Once the bounded deadline
284
+ // expires the closed runtime must not keep those request graphs alive.
285
+ this.#activeMcpServers.clear();
286
+ this.#inFlight.clear();
287
+ this.#sockets.clear();
288
+ }
289
+ #admitMcpRequest() {
290
+ if (this.#admittedRequestCount >= this.#maxConcurrentRequests)
291
+ return undefined;
292
+ this.#admittedRequestCount += 1;
293
+ let released = false;
294
+ return () => {
295
+ if (released)
296
+ return;
297
+ released = true;
298
+ this.#admittedRequestCount = Math.max(0, this.#admittedRequestCount - 1);
299
+ };
300
+ }
301
+ #handleClientError(error, socket) {
302
+ if (this.#clientErrorSockets.has(socket)) {
303
+ socket.destroy();
304
+ return;
305
+ }
306
+ this.#clientErrorSockets.add(socket);
307
+ const code = safeClientErrorCode(error);
308
+ const status = code === "ERR_HTTP_REQUEST_TIMEOUT"
309
+ ? 408
310
+ : code === "HPE_HEADER_OVERFLOW"
311
+ ? 431
312
+ : 400;
313
+ const reason = status === 408
314
+ ? "request_timeout"
315
+ : status === 400
316
+ ? "malformed_request"
317
+ : "invalid_protocol";
318
+ const message = status === 408 ? "Request timeout." : "Invalid request.";
319
+ const body = `${JSON.stringify({
320
+ jsonrpc: "2.0",
321
+ error: { code: -32600, message },
322
+ id: null,
323
+ })}\n`;
324
+ const activeRequest = this.#activeParserRequests.get(socket);
325
+ const correlationId = activeRequest?.correlationId ?? (0, node_crypto_1.randomUUID)();
326
+ if (activeRequest) {
327
+ this.#activeParserRequests.delete(socket);
328
+ activeRequest.finish(status, reason);
329
+ }
330
+ else {
331
+ const observation = beginRequestObservation(this.#observability);
332
+ if (observation) {
333
+ try {
334
+ suppressUnexpectedThenable(observation.finish({
335
+ correlationId,
336
+ outcome: "rejected",
337
+ reason,
338
+ statusCode: status,
339
+ }));
340
+ }
341
+ catch {
342
+ // Parser-boundary telemetry is optional and cannot affect the socket.
343
+ }
344
+ }
345
+ }
346
+ if (socket.destroyed || !socket.writable)
347
+ return;
348
+ const statusText = status === 408
349
+ ? "Request Timeout"
350
+ : status === 431
351
+ ? "Request Header Fields Too Large"
352
+ : "Bad Request";
353
+ try {
354
+ socket.end(`HTTP/1.1 ${status} ${statusText}\r\n` +
355
+ "Connection: close\r\n" +
356
+ "Cache-Control: no-store\r\n" +
357
+ "Content-Type: application/json; charset=utf-8\r\n" +
358
+ `${REQUEST_CORRELATION_HEADER}: ${correlationId}\r\n` +
359
+ `Content-Length: ${Buffer.byteLength(body, "utf8")}\r\n\r\n` +
360
+ body);
361
+ }
362
+ catch {
363
+ socket.destroy();
364
+ }
365
+ }
366
+ #closeLateFactoryServer(candidate) {
367
+ if (!(candidate instanceof mcp_js_1.McpServer) || candidate.isConnected())
368
+ return;
369
+ this.#activeMcpServers.add(candidate);
370
+ const closing = closeMcpServer(candidate);
371
+ void settleWithin(closing, Math.min(MCP_SERVER_CLOSE_TIMEOUT_MS, this.#requestPolicyLimits.requestDeadlineMs)).then((closed) => {
372
+ if (closed === true) {
373
+ this.#activeMcpServers.delete(candidate);
374
+ }
375
+ else if (closed === false &&
376
+ (this.#state === "closing" || this.#state === "closed")) {
377
+ // The normal shutdown sweep may already have passed while the factory
378
+ // was resolving. Retry once now that shutdown owns all remaining work.
379
+ void closeMcpServer(candidate).then((retried) => {
380
+ if (retried)
381
+ this.#activeMcpServers.delete(candidate);
382
+ });
383
+ }
384
+ else if (closed === "deadline") {
385
+ void closing.then((eventuallyClosed) => {
386
+ if (eventuallyClosed)
387
+ this.#activeMcpServers.delete(candidate);
388
+ });
389
+ }
390
+ });
391
+ }
392
+ async #handleNodeRequest(request, response) {
393
+ const requestCorrelationId = (0, node_crypto_1.randomUUID)();
394
+ const requestObservation = beginRequestObservation(this.#observability);
395
+ const observationState = { identity: undefined };
396
+ let observedReason = null;
397
+ let activeRequestDeadline;
398
+ let expectsToolAudit = false;
399
+ let toolAuditObserved = false;
400
+ let observationFinished = false;
401
+ let parserErrorHandled = false;
402
+ const finishObservation = (connectionClosedEarly, explicitStatusCode) => {
403
+ if (observationFinished || !requestObservation)
404
+ return;
405
+ observationFinished = true;
406
+ const statusCode = explicitStatusCode ??
407
+ (connectionClosedEarly
408
+ ? observedReason === "client_disconnected"
409
+ ? 499
410
+ : observedReason === "request_timeout"
411
+ ? 408
412
+ : observedReason === "service_unavailable"
413
+ ? 503
414
+ : 500
415
+ : response.statusCode);
416
+ const completion = statusCode < 400 && expectsToolAudit && !toolAuditObserved
417
+ ? {
418
+ outcome: "rejected",
419
+ reason: "tool_input_rejected",
420
+ statusCode,
421
+ }
422
+ : classifyHttpCompletion(statusCode, observedReason);
423
+ try {
424
+ suppressUnexpectedThenable(requestObservation.finish({
425
+ correlationId: requestCorrelationId,
426
+ ...(observationState.identity === undefined
427
+ ? {}
428
+ : { identity: observationState.identity }),
429
+ ...completion,
430
+ }));
431
+ }
432
+ catch {
433
+ // Optional telemetry cannot affect HTTP completion or process safety.
434
+ }
435
+ };
436
+ const activeParserRequest = Object.freeze({
437
+ correlationId: requestCorrelationId,
438
+ finish: (statusCode, reason) => {
439
+ parserErrorHandled = true;
440
+ observedReason = reason;
441
+ finishObservation(true, statusCode);
442
+ },
443
+ });
444
+ this.#activeParserRequests.set(request.socket, activeParserRequest);
445
+ const clearActiveParserRequest = () => {
446
+ if (this.#activeParserRequests.get(request.socket) === activeParserRequest) {
447
+ this.#activeParserRequests.delete(request.socket);
448
+ }
449
+ };
450
+ response.setHeader(REQUEST_CORRELATION_HEADER, requestCorrelationId);
451
+ const handleClientDisconnect = () => {
452
+ if (response.writableFinished || observationFinished)
453
+ return;
454
+ const abortError = activeRequestDeadline?.abortError;
455
+ if (abortError instanceof HttpRequestDeadlineError) {
456
+ observedReason = "request_timeout";
457
+ }
458
+ else if (abortError instanceof HttpRequestCancellationError) {
459
+ observedReason = cancellationObservationReason(abortError);
460
+ }
461
+ else {
462
+ observedReason = "client_disconnected";
463
+ activeRequestDeadline?.cancel("client_disconnected");
464
+ }
465
+ finishObservation(true);
466
+ };
467
+ response.once("finish", () => {
468
+ clearActiveParserRequest();
469
+ finishObservation(false);
470
+ disposeUnreadRequestBody(request);
471
+ });
472
+ response.once("close", () => {
473
+ handleClientDisconnect();
474
+ });
475
+ request.once("aborted", () => {
476
+ handleClientDisconnect();
477
+ });
478
+ const pathname = requestPath(request.url);
479
+ // Host and Origin are transport authority, so reject them before routing,
480
+ // authentication, body parsing, or any application dependency. Passing an
481
+ // undefined method deliberately defers MCP content checks until after the
482
+ // established authentication/rate-limit boundary.
483
+ const authorityDecision = (0, http_request_policy_js_1.inspectHttpRequest)(this.#requestPolicy, {
484
+ rawHeaders: request.rawHeaders,
485
+ method: undefined,
486
+ pathname,
487
+ configuredHost: this.#host,
488
+ localAddress: request.socket.localAddress,
489
+ localPort: request.socket.localPort,
490
+ remoteAddress: request.socket.remoteAddress,
491
+ });
492
+ applyPolicyResponseHeaders(response, authorityDecision.responseHeaders);
493
+ if (authorityDecision.kind === "reject") {
494
+ observedReason = policyObservationReason(authorityDecision.reason);
495
+ writePolicyRejection(response, authorityDecision);
496
+ return;
497
+ }
498
+ if (pathname === exports.MCP_LIVENESS_PATH) {
499
+ if (!isHealthMethod(request.method)) {
500
+ observedReason = "method_not_allowed";
501
+ writeHealthMethodNotAllowed(response);
502
+ return;
503
+ }
504
+ writeHealthResponse(request, response, 200, LIVE_BODY);
505
+ return;
506
+ }
507
+ if (pathname === exports.MCP_READINESS_PATH) {
508
+ if (!isHealthMethod(request.method)) {
509
+ observedReason = "method_not_allowed";
510
+ writeHealthMethodNotAllowed(response);
511
+ return;
512
+ }
513
+ const ready = this.isReady();
514
+ if (!ready)
515
+ observedReason = "service_unavailable";
516
+ writeHealthResponse(request, response, ready ? 200 : 503, ready ? READY_BODY : NOT_READY_BODY);
517
+ return;
518
+ }
519
+ // Health probes describe process/runtime lifecycle and must not be
520
+ // starved by an MCP client's shared source bucket (for example behind a
521
+ // reverse proxy). Every non-health route remains source-limited before
522
+ // authentication or server construction.
523
+ if (this.#rateLimiter) {
524
+ let preAuthentication;
525
+ try {
526
+ preAuthentication = this.#rateLimiter.checkPreAuthentication(request.socket.remoteAddress ?? "unknown");
527
+ if (preAuthentication.allowed) {
528
+ // Continue into the cheap route/authentication boundary.
529
+ }
530
+ else {
531
+ observedReason = "pre_auth_rate_limited";
532
+ writeRateLimitRejection(response, preAuthentication);
533
+ return;
534
+ }
535
+ }
536
+ catch {
537
+ observedReason = "pre_auth_rate_limited";
538
+ writeRateLimitRejection(response, {});
539
+ return;
540
+ }
541
+ }
542
+ if (this.#state !== "listening") {
543
+ observedReason = "service_unavailable";
544
+ writeJsonRpcError(response, 503, -32000, "Service unavailable.");
545
+ return;
546
+ }
547
+ if (pathname !== exports.MCP_HTTP_PATH) {
548
+ observedReason = "not_found";
549
+ writeJsonRpcError(response, 404, -32000, "Not found.");
550
+ return;
551
+ }
552
+ if (request.method === "OPTIONS") {
553
+ const preflight = (0, http_request_policy_js_1.inspectHttpRequest)(this.#requestPolicy, {
554
+ rawHeaders: request.rawHeaders,
555
+ method: request.method,
556
+ pathname,
557
+ configuredHost: this.#host,
558
+ localAddress: request.socket.localAddress,
559
+ localPort: request.socket.localPort,
560
+ remoteAddress: request.socket.remoteAddress,
561
+ });
562
+ applyPolicyResponseHeaders(response, preflight.responseHeaders);
563
+ if (preflight.kind === "preflight") {
564
+ writeEmptyResponse(response, preflight.status, preflight.responseHeaders);
565
+ }
566
+ else if (preflight.kind === "reject") {
567
+ observedReason = policyObservationReason(preflight.reason);
568
+ writePolicyRejection(response, preflight);
569
+ }
570
+ else {
571
+ observedReason = "method_not_allowed";
572
+ writeJsonRpcError(response, 405, -32000, "Method not allowed.", {
573
+ allow: "POST",
574
+ });
575
+ }
576
+ return;
577
+ }
578
+ if (request.method !== "POST") {
579
+ observedReason = "method_not_allowed";
580
+ writeJsonRpcError(response, 405, -32000, "Method not allowed.", {
581
+ allow: "POST",
582
+ });
583
+ return;
584
+ }
585
+ const releaseAdmission = this.#admitMcpRequest();
586
+ if (!releaseAdmission) {
587
+ observedReason = "concurrency_limited";
588
+ writeConcurrencyRejection(request, response);
589
+ return;
590
+ }
591
+ const requestDeadline = new HttpRequestDeadline(this.#requestPolicyLimits.requestDeadlineMs);
592
+ activeRequestDeadline = requestDeadline;
593
+ this.#activeRequestDeadlines.add(requestDeadline);
594
+ try {
595
+ let identity;
596
+ try {
597
+ const authenticationRequest = (0, http_auth_js_1.httpAuthenticationRequestFromRawHeaders)(request.rawHeaders);
598
+ identity = await requestDeadline.run((0, http_auth_js_1.authenticateHttpRequest)(this.#authenticationProvider, authenticationRequest, requestDeadline.signal));
599
+ }
600
+ catch (error) {
601
+ if (error instanceof HttpRequestDeadlineError) {
602
+ observedReason = "request_timeout";
603
+ writeRequestTimeout(request, response);
604
+ return;
605
+ }
606
+ if (error instanceof HttpRequestCancellationError)
607
+ return;
608
+ const failure = (0, http_auth_js_1.safeHttpAuthenticationFailure)(error);
609
+ observedReason = failure.status === 403 ? "forbidden" : "unauthorized";
610
+ writeResponse(response, failure.status, failure.headers, failure.body);
611
+ return;
612
+ }
613
+ observationState.identity = identity;
614
+ if (this.#rateLimiter) {
615
+ try {
616
+ const authenticated = this.#rateLimiter.checkAuthenticated(identity);
617
+ if (!authenticated.allowed) {
618
+ observedReason = "identity_rate_limited";
619
+ writeRateLimitRejection(response, authenticated);
620
+ return;
621
+ }
622
+ }
623
+ catch {
624
+ observedReason = "identity_rate_limited";
625
+ writeRateLimitRejection(response, {});
626
+ return;
627
+ }
628
+ }
629
+ const contentDecision = (0, http_request_policy_js_1.inspectHttpRequest)(this.#requestPolicy, {
630
+ rawHeaders: request.rawHeaders,
631
+ method: request.method,
632
+ pathname,
633
+ configuredHost: this.#host,
634
+ localAddress: request.socket.localAddress,
635
+ localPort: request.socket.localPort,
636
+ remoteAddress: request.socket.remoteAddress,
637
+ });
638
+ applyPolicyResponseHeaders(response, contentDecision.responseHeaders);
639
+ if (contentDecision.kind === "reject") {
640
+ observedReason = policyObservationReason(contentDecision.reason);
641
+ writePolicyRejection(response, contentDecision);
642
+ return;
643
+ }
644
+ if (contentDecision.kind !== "allow") {
645
+ observedReason = "invalid_protocol";
646
+ writeJsonRpcError(response, 400, -32600, "Invalid request.");
647
+ return;
648
+ }
649
+ if (this.#state !== "listening" || request.aborted || response.destroyed) {
650
+ observedReason = "service_unavailable";
651
+ writeJsonRpcError(response, 503, -32000, "Service unavailable.");
652
+ return;
653
+ }
654
+ if (!hasSupportedProtocolHeader(request)) {
655
+ observedReason = "invalid_protocol";
656
+ writeJsonRpcError(response, 400, -32600, "Unsupported MCP protocol version.");
657
+ return;
658
+ }
659
+ let parsedBody;
660
+ try {
661
+ parsedBody = await requestDeadline.run(readBoundedJsonBody(request, this.#requestPolicyLimits.maxBodyBytes, this.#requestPolicyLimits.bodyReadTimeoutMs));
662
+ }
663
+ catch (error) {
664
+ if (parserErrorHandled)
665
+ return;
666
+ if (error instanceof HttpBodyReadError && error.kind === "too_large") {
667
+ observedReason = "request_too_large";
668
+ writeJsonRpcError(response, 413, -32600, "Request body is too large.");
669
+ }
670
+ else if (error instanceof HttpRequestDeadlineError ||
671
+ (error instanceof HttpBodyReadError && error.kind === "timeout")) {
672
+ observedReason = "request_timeout";
673
+ writeRequestTimeout(request, response);
674
+ }
675
+ else if (error instanceof HttpRequestCancellationError) {
676
+ observedReason = cancellationObservationReason(error);
677
+ }
678
+ else if (error instanceof HttpBodyReadError &&
679
+ error.kind === "aborted") {
680
+ observedReason = request.aborted
681
+ ? "client_disconnected"
682
+ : "malformed_request";
683
+ if (!response.destroyed) {
684
+ writeJsonRpcError(response, 400, -32700, "Malformed JSON request.");
685
+ }
686
+ }
687
+ else {
688
+ observedReason = "malformed_request";
689
+ writeJsonRpcError(response, 400, -32700, "Malformed JSON request.");
690
+ }
691
+ return;
692
+ }
693
+ if (Array.isArray(parsedBody)) {
694
+ observedReason = "invalid_protocol";
695
+ writeJsonRpcError(response, 400, -32600, "JSON-RPC batches are not supported.");
696
+ return;
697
+ }
698
+ const fallbackTool = createFallbackToolObservation(this.#observability, parsedBody, identity, requestCorrelationId);
699
+ expectsToolAudit = fallbackTool !== undefined;
700
+ const context = Object.freeze({
701
+ identity,
702
+ signal: requestDeadline.signal,
703
+ requestMetadataProvider: (0, http_auth_js_1.createAuthenticatedRequestMetadataProvider)(identity, createHttpCorrelationIdFactory(requestCorrelationId)),
704
+ markToolAuditObserved: () => {
705
+ toolAuditObserved = true;
706
+ },
707
+ });
708
+ let ownedMcpServer;
709
+ let factoryState = "pending";
710
+ let earlyFactoryResult;
711
+ const factoryResult = Promise.resolve().then(() => this.#createMcpServer(context));
712
+ void factoryResult.then((candidate) => {
713
+ if (factoryState === "abandoned") {
714
+ this.#closeLateFactoryServer(candidate);
715
+ }
716
+ else if (factoryState === "pending") {
717
+ earlyFactoryResult = candidate;
718
+ }
719
+ }, () => {
720
+ // requestDeadline.run observes an in-time rejection. A rejection that
721
+ // arrives after cancellation is intentionally consumed here.
722
+ });
723
+ try {
724
+ const candidate = await requestDeadline.run(factoryResult);
725
+ factoryState = "accepted";
726
+ earlyFactoryResult = undefined;
727
+ if (!(candidate instanceof mcp_js_1.McpServer)) {
728
+ throw new TypeError("HTTP server factory must return an McpServer");
729
+ }
730
+ if (candidate.isConnected()) {
731
+ throw new TypeError("HTTP server factory must return an unconnected McpServer");
732
+ }
733
+ // Ownership transfers only after the candidate passes both checks. An
734
+ // invalid return or caller-owned connected server is never closed here.
735
+ ownedMcpServer = candidate;
736
+ if (this.#state !== "listening" || request.aborted || response.destroyed) {
737
+ observedReason = "service_unavailable";
738
+ writeJsonRpcError(response, 503, -32000, "Service unavailable.");
739
+ return;
740
+ }
741
+ this.#activeMcpServers.add(ownedMcpServer);
742
+ const transport = new streamableHttp_js_1.StreamableHTTPServerTransport({
743
+ sessionIdGenerator: undefined,
744
+ enableJsonResponse: true,
745
+ });
746
+ await requestDeadline.run(ownedMcpServer.connect(transport));
747
+ await requestDeadline.run(transport.handleRequest(request, response, parsedBody));
748
+ }
749
+ catch (error) {
750
+ if (error instanceof HttpRequestDeadlineError) {
751
+ factoryState = "abandoned";
752
+ if (earlyFactoryResult !== undefined) {
753
+ this.#closeLateFactoryServer(earlyFactoryResult);
754
+ earlyFactoryResult = undefined;
755
+ }
756
+ observedReason = "request_timeout";
757
+ if (!response.headersSent && !response.destroyed) {
758
+ writeRequestTimeout(request, response);
759
+ }
760
+ else if (!response.writableEnded) {
761
+ response.destroy();
762
+ }
763
+ }
764
+ else if (error instanceof HttpRequestCancellationError) {
765
+ factoryState = "abandoned";
766
+ if (earlyFactoryResult !== undefined) {
767
+ this.#closeLateFactoryServer(earlyFactoryResult);
768
+ earlyFactoryResult = undefined;
769
+ }
770
+ observedReason = cancellationObservationReason(error);
771
+ }
772
+ else if (!response.headersSent && !response.destroyed) {
773
+ observedReason = "internal_error";
774
+ writeJsonRpcError(response, 500, -32603, "Internal server error.");
775
+ }
776
+ else if (!response.writableEnded) {
777
+ observedReason = "internal_error";
778
+ response.destroy();
779
+ }
780
+ }
781
+ finally {
782
+ if (ownedMcpServer) {
783
+ const serverToClose = ownedMcpServer;
784
+ const closing = closeMcpServer(serverToClose);
785
+ const closed = await settleWithin(closing, Math.min(MCP_SERVER_CLOSE_TIMEOUT_MS, this.#requestPolicyLimits.requestDeadlineMs));
786
+ if (closed === true) {
787
+ this.#activeMcpServers.delete(serverToClose);
788
+ }
789
+ else if (closed === "deadline") {
790
+ // Keep timed-out resources owned by the runtime so a later forced
791
+ // runtime close can retry them. Remove them if the original close
792
+ // eventually succeeds in the meantime.
793
+ void closing.then((eventuallyClosed) => {
794
+ if (eventuallyClosed)
795
+ this.#activeMcpServers.delete(serverToClose);
796
+ });
797
+ }
798
+ }
799
+ if (fallbackTool &&
800
+ !toolAuditObserved &&
801
+ response.statusCode < 400) {
802
+ try {
803
+ suppressUnexpectedThenable(fallbackTool.observation.finish(fallbackTool.record));
804
+ }
805
+ catch {
806
+ // Pre-validation observability is isolated from protocol behavior.
807
+ }
808
+ }
809
+ }
810
+ }
811
+ finally {
812
+ activeRequestDeadline = undefined;
813
+ this.#activeRequestDeadlines.delete(requestDeadline);
814
+ requestDeadline.dispose();
815
+ releaseAdmission();
816
+ }
817
+ }
818
+ }
819
+ function createFallbackToolObservation(observability, parsedBody, identity, requestSeed) {
820
+ if (!observability || typeof parsedBody !== "object" || parsedBody === null) {
821
+ return undefined;
822
+ }
823
+ try {
824
+ const body = parsedBody;
825
+ const params = body.params;
826
+ if (body.method !== "tools/call" ||
827
+ (typeof body.id !== "string" && typeof body.id !== "number") ||
828
+ typeof params !== "object" ||
829
+ params === null) {
830
+ return undefined;
831
+ }
832
+ const tool = Reflect.get(params, "name");
833
+ if (typeof tool !== "string" || !/^sn_[a-z0-9_]{1,61}$/u.test(tool)) {
834
+ return undefined;
835
+ }
836
+ const correlationId = createHttpCorrelationIdFactory(requestSeed)({
837
+ tool,
838
+ requestId: body.id,
839
+ });
840
+ const observation = observability.beginTool();
841
+ if (!observation || typeof observation.finish !== "function")
842
+ return undefined;
843
+ const record = (0, execution_context_js_1.createPreContextAuditRecord)({
844
+ tool,
845
+ request: { correlationId, identity },
846
+ reason: "input_validation_failed",
847
+ });
848
+ return Object.freeze({ observation, record });
849
+ }
850
+ catch {
851
+ return undefined;
852
+ }
853
+ }
854
+ class HttpBodyReadError extends Error {
855
+ kind;
856
+ constructor(kind) {
857
+ super("HTTP request body rejected");
858
+ this.kind = kind;
859
+ this.name = "HttpBodyReadError";
860
+ }
861
+ }
862
+ class HttpRequestDeadlineError extends Error {
863
+ constructor() {
864
+ super("HTTP request deadline exceeded");
865
+ this.name = "HttpRequestDeadlineError";
866
+ }
867
+ }
868
+ class HttpRequestCancellationError extends Error {
869
+ kind;
870
+ constructor(kind) {
871
+ super("HTTP request cancelled");
872
+ this.kind = kind;
873
+ this.name = "HttpRequestCancellationError";
874
+ }
875
+ }
876
+ const REQUEST_ABORTED = Symbol("http-request-aborted");
877
+ /** One bounded deadline shared by every asynchronous stage of an MCP POST. */
878
+ class HttpRequestDeadline {
879
+ #controller = (0, http_request_signal_js_1.createHttpRequestSignalController)();
880
+ #expiration;
881
+ #resolveExpiration;
882
+ #timer;
883
+ #error;
884
+ #disposed = false;
885
+ constructor(timeoutMs) {
886
+ this.#expiration = new Promise((resolve) => {
887
+ this.#resolveExpiration = resolve;
888
+ this.#timer = setTimeout(() => {
889
+ this.#abort(new HttpRequestDeadlineError(), "deadline");
890
+ }, timeoutMs);
891
+ this.#timer.unref?.();
892
+ });
893
+ }
894
+ get signal() {
895
+ return this.#controller.signal;
896
+ }
897
+ get abortError() {
898
+ return this.#error;
899
+ }
900
+ cancel(kind) {
901
+ this.#abort(new HttpRequestCancellationError(kind), kind);
902
+ }
903
+ async run(operation) {
904
+ if (this.#error)
905
+ throw this.#error;
906
+ if (this.#disposed)
907
+ throw new HttpRequestDeadlineError();
908
+ const outcome = await Promise.race([operation, this.#expiration]);
909
+ if (typeof outcome === "object" &&
910
+ outcome !== null &&
911
+ Reflect.get(outcome, "marker") === REQUEST_ABORTED) {
912
+ throw outcome.error;
913
+ }
914
+ return outcome;
915
+ }
916
+ dispose() {
917
+ if (this.#disposed)
918
+ return;
919
+ this.#disposed = true;
920
+ if (this.#timer)
921
+ clearTimeout(this.#timer);
922
+ this.#resolveExpiration = undefined;
923
+ }
924
+ #abort(error, kind) {
925
+ if (this.#error || this.#disposed)
926
+ return;
927
+ this.#error = error;
928
+ if (this.#timer)
929
+ clearTimeout(this.#timer);
930
+ this.#controller.abort(kind, error);
931
+ this.#resolveExpiration?.(Object.freeze({ marker: REQUEST_ABORTED, error }));
932
+ this.#resolveExpiration = undefined;
933
+ }
934
+ }
935
+ function hasSupportedProtocolHeader(request) {
936
+ const candidate = request.headers["mcp-protocol-version"];
937
+ if (candidate === undefined)
938
+ return true;
939
+ return (typeof candidate === "string" &&
940
+ types_js_1.SUPPORTED_PROTOCOL_VERSIONS.includes(candidate));
941
+ }
942
+ async function readBoundedJsonBody(request, maximumBytes, timeoutMs) {
943
+ let timer;
944
+ const timeout = new Promise((_resolve, reject) => {
945
+ timer = setTimeout(() => reject(new HttpBodyReadError("timeout")), timeoutMs);
946
+ timer.unref?.();
947
+ });
948
+ const consume = async () => {
949
+ return new Promise((resolve, reject) => {
950
+ const chunks = [];
951
+ let total = 0;
952
+ let settled = false;
953
+ const cleanup = () => {
954
+ request.off("data", onData);
955
+ request.off("end", onEnd);
956
+ request.off("aborted", onAborted);
957
+ request.off("error", onError);
958
+ };
959
+ const rejectOnce = (error) => {
960
+ if (settled)
961
+ return;
962
+ settled = true;
963
+ cleanup();
964
+ reject(error);
965
+ };
966
+ const onData = (candidate) => {
967
+ if (settled)
968
+ return;
969
+ const chunk = Buffer.isBuffer(candidate)
970
+ ? candidate
971
+ : Buffer.from(candidate);
972
+ total += chunk.length;
973
+ if (total > maximumBytes) {
974
+ rejectOnce(new HttpBodyReadError("too_large"));
975
+ return;
976
+ }
977
+ chunks.push(chunk);
978
+ };
979
+ const onEnd = () => {
980
+ if (settled)
981
+ return;
982
+ settled = true;
983
+ cleanup();
984
+ try {
985
+ resolve(JSON.parse(Buffer.concat(chunks, total).toString("utf8")));
986
+ }
987
+ catch {
988
+ reject(new HttpBodyReadError("malformed"));
989
+ }
990
+ };
991
+ const onAborted = () => rejectOnce(new HttpBodyReadError("aborted"));
992
+ const onError = () => rejectOnce(new HttpBodyReadError(request.aborted ? "aborted" : "malformed"));
993
+ request.on("data", onData);
994
+ request.once("end", onEnd);
995
+ request.once("aborted", onAborted);
996
+ request.once("error", onError);
997
+ });
998
+ };
999
+ try {
1000
+ return await Promise.race([consume(), timeout]);
1001
+ }
1002
+ finally {
1003
+ if (timer)
1004
+ clearTimeout(timer);
1005
+ }
1006
+ }
1007
+ function beginRequestObservation(observability) {
1008
+ if (!observability)
1009
+ return undefined;
1010
+ try {
1011
+ const observation = observability.beginRequest();
1012
+ return observation && typeof observation.finish === "function"
1013
+ ? observation
1014
+ : undefined;
1015
+ }
1016
+ catch {
1017
+ return undefined;
1018
+ }
1019
+ }
1020
+ function safeClientErrorCode(error) {
1021
+ try {
1022
+ if (typeof error !== "object" || error === null)
1023
+ return undefined;
1024
+ const candidate = Reflect.get(error, "code");
1025
+ return typeof candidate === "string" && candidate.length <= 64
1026
+ ? candidate
1027
+ : undefined;
1028
+ }
1029
+ catch {
1030
+ return undefined;
1031
+ }
1032
+ }
1033
+ function suppressUnexpectedThenable(value) {
1034
+ if (((typeof value === "object" && value !== null) ||
1035
+ typeof value === "function") &&
1036
+ typeof Reflect.get(value, "then") === "function") {
1037
+ void Promise.resolve(value).catch(() => { });
1038
+ }
1039
+ }
1040
+ function classifyHttpCompletion(statusCode, explicitReason) {
1041
+ if (statusCode < 400) {
1042
+ return { outcome: "success", reason: null, statusCode };
1043
+ }
1044
+ const reason = explicitReason ?? reasonFromHttpStatus(statusCode);
1045
+ return {
1046
+ outcome: statusCode >= 500 && reason === "internal_error" ? "error" : "rejected",
1047
+ reason,
1048
+ statusCode,
1049
+ };
1050
+ }
1051
+ function reasonFromHttpStatus(statusCode) {
1052
+ switch (statusCode) {
1053
+ case 400:
1054
+ return "malformed_request";
1055
+ case 401:
1056
+ return "unauthorized";
1057
+ case 403:
1058
+ return "forbidden";
1059
+ case 404:
1060
+ return "not_found";
1061
+ case 405:
1062
+ return "method_not_allowed";
1063
+ case 408:
1064
+ return "request_timeout";
1065
+ case 413:
1066
+ return "request_too_large";
1067
+ case 415:
1068
+ return "invalid_content_type";
1069
+ case 429:
1070
+ return "pre_auth_rate_limited";
1071
+ case 503:
1072
+ return "service_unavailable";
1073
+ default:
1074
+ return statusCode >= 500 ? "internal_error" : "invalid_protocol";
1075
+ }
1076
+ }
1077
+ /** Keep MCP request linkage while namespacing it to one authenticated HTTP request. */
1078
+ function createHttpCorrelationIdFactory(requestSeed) {
1079
+ return (invocation) => `${(0, http_auth_js_1.correlationIdFromMcpRequest)(invocation)}-${requestSeed}`;
1080
+ }
1081
+ function requestPath(rawUrl) {
1082
+ if (typeof rawUrl !== "string")
1083
+ return undefined;
1084
+ try {
1085
+ return new URL(rawUrl, "http://mcp.invalid").pathname;
1086
+ }
1087
+ catch {
1088
+ return undefined;
1089
+ }
1090
+ }
1091
+ function writeHealthResponse(request, response, status, body) {
1092
+ writeResponse(response, status, JSON_ERROR_HEADERS, body, request.method === "HEAD");
1093
+ }
1094
+ function isHealthMethod(method) {
1095
+ return method === "GET" || method === "HEAD";
1096
+ }
1097
+ function writeHealthMethodNotAllowed(response) {
1098
+ writeJsonRpcError(response, 405, -32000, "Method not allowed.", {
1099
+ allow: "GET, HEAD",
1100
+ });
1101
+ }
1102
+ function writeRateLimitRejection(response, decision) {
1103
+ const rejection = (0, http_observability_js_1.safeHttpRateLimitRejection)(decision);
1104
+ writeResponse(response, rejection.status, rejection.headers, rejection.body);
1105
+ }
1106
+ function applyPolicyResponseHeaders(response, headers) {
1107
+ if (response.headersSent || response.destroyed)
1108
+ return;
1109
+ for (const [name, value] of Object.entries(headers)) {
1110
+ if (name.toLowerCase() === REQUEST_CORRELATION_HEADER)
1111
+ continue;
1112
+ response.setHeader(name, value);
1113
+ }
1114
+ }
1115
+ function policyObservationReason(reason) {
1116
+ switch (reason) {
1117
+ case "disallowed_origin":
1118
+ case "invalid_preflight":
1119
+ return "forbidden";
1120
+ case "invalid_content_type":
1121
+ return "invalid_content_type";
1122
+ case "request_too_large":
1123
+ return "request_too_large";
1124
+ case "invalid_host":
1125
+ case "disallowed_host":
1126
+ case "invalid_origin":
1127
+ return "invalid_protocol";
1128
+ }
1129
+ }
1130
+ function cancellationObservationReason(error) {
1131
+ return error.kind === "shutdown" ? "service_unavailable" : "client_disconnected";
1132
+ }
1133
+ function writePolicyRejection(response, decision) {
1134
+ const [code, message] = decision.status === 403
1135
+ ? [-32000, "Forbidden."]
1136
+ : decision.status === 413
1137
+ ? [-32600, "Request body is too large."]
1138
+ : decision.status === 415
1139
+ ? [-32000, "Unsupported media type."]
1140
+ : decision.status === 421
1141
+ ? [-32600, "Misdirected request."]
1142
+ : [-32600, "Invalid request."];
1143
+ writeJsonRpcError(response, decision.status, code, message, decision.responseHeaders);
1144
+ }
1145
+ function writeEmptyResponse(response, status, headers) {
1146
+ if (response.headersSent || response.destroyed)
1147
+ return;
1148
+ const correlationId = response.getHeader(REQUEST_CORRELATION_HEADER);
1149
+ response.writeHead(status, {
1150
+ ...headers,
1151
+ ...(typeof correlationId === "string"
1152
+ ? { [REQUEST_CORRELATION_HEADER]: correlationId }
1153
+ : {}),
1154
+ "content-length": "0",
1155
+ });
1156
+ response.end();
1157
+ }
1158
+ /**
1159
+ * Consume only a small, time-bounded remainder after an early response.
1160
+ *
1161
+ * Rejected requests can still be streaming a declared body after the response
1162
+ * has flushed. Leaving that IncomingMessage paused retains its socket until the
1163
+ * much longer parser timeout. A fully received small remainder remains eligible
1164
+ * for keep-alive; a stalled or larger remainder is destroyed deterministically.
1165
+ */
1166
+ function disposeUnreadRequestBody(request) {
1167
+ if (request.destroyed || request.readableEnded)
1168
+ return;
1169
+ let consumedBytes = 0;
1170
+ let settled = false;
1171
+ const cleanup = () => {
1172
+ request.off("data", onData);
1173
+ request.off("end", onEnd);
1174
+ request.off("aborted", onClosed);
1175
+ request.off("close", onClosed);
1176
+ request.off("error", onClosed);
1177
+ clearTimeout(timer);
1178
+ };
1179
+ const settle = (destroy) => {
1180
+ if (settled)
1181
+ return;
1182
+ settled = true;
1183
+ cleanup();
1184
+ if (destroy && !request.destroyed)
1185
+ request.destroy();
1186
+ };
1187
+ const onData = (candidate) => {
1188
+ const length = Buffer.isBuffer(candidate)
1189
+ ? candidate.length
1190
+ : candidate.byteLength;
1191
+ consumedBytes += length;
1192
+ if (consumedBytes > exports.MAX_REJECTED_BODY_DRAIN_BYTES)
1193
+ settle(true);
1194
+ };
1195
+ const onEnd = () => settle(false);
1196
+ const onClosed = () => settle(false);
1197
+ request.on("data", onData);
1198
+ request.once("end", onEnd);
1199
+ request.once("aborted", onClosed);
1200
+ request.once("close", onClosed);
1201
+ request.once("error", onClosed);
1202
+ const timer = setTimeout(() => settle(true), exports.REJECTED_BODY_DRAIN_TIMEOUT_MS);
1203
+ timer.unref?.();
1204
+ request.resume();
1205
+ }
1206
+ function writeRequestTimeout(request, response) {
1207
+ if (response.destroyed)
1208
+ return;
1209
+ response.shouldKeepAlive = false;
1210
+ writeJsonRpcError(response, 408, -32000, "Request timeout.", {
1211
+ connection: "close",
1212
+ });
1213
+ if (response.writableFinished) {
1214
+ request.destroy();
1215
+ }
1216
+ else {
1217
+ response.once("finish", () => request.destroy());
1218
+ }
1219
+ }
1220
+ function writeConcurrencyRejection(request, response) {
1221
+ if (response.destroyed)
1222
+ return;
1223
+ response.shouldKeepAlive = false;
1224
+ writeJsonRpcError(response, 503, -32000, "Service temporarily busy.", {
1225
+ connection: "close",
1226
+ "retry-after": "1",
1227
+ });
1228
+ if (response.writableFinished) {
1229
+ request.destroy();
1230
+ }
1231
+ else {
1232
+ response.once("finish", () => request.destroy());
1233
+ }
1234
+ }
1235
+ function writeJsonRpcError(response, status, code, message, headers = {}) {
1236
+ writeResponse(response, status, { ...JSON_ERROR_HEADERS, ...headers }, `${JSON.stringify({
1237
+ jsonrpc: "2.0",
1238
+ error: { code, message },
1239
+ id: null,
1240
+ })}\n`);
1241
+ }
1242
+ function writeResponse(response, status, headers, body, headOnly = false) {
1243
+ if (response.headersSent || response.destroyed)
1244
+ return;
1245
+ const correlationId = response.getHeader(REQUEST_CORRELATION_HEADER);
1246
+ response.writeHead(status, {
1247
+ ...headers,
1248
+ ...(typeof correlationId === "string"
1249
+ ? { [REQUEST_CORRELATION_HEADER]: correlationId }
1250
+ : {}),
1251
+ "content-length": Buffer.byteLength(body, "utf8"),
1252
+ });
1253
+ response.end(headOnly ? undefined : body);
1254
+ }
1255
+ function closeNodeServer(server) {
1256
+ return new Promise((resolve, reject) => {
1257
+ server.close((error) => (error ? reject(error) : resolve()));
1258
+ });
1259
+ }
1260
+ /** Convert synchronous throws and rejected cleanup into a bounded boolean. */
1261
+ function closeMcpServer(server) {
1262
+ try {
1263
+ return Promise.resolve(server.close()).then(() => true, () => false);
1264
+ }
1265
+ catch {
1266
+ return Promise.resolve(false);
1267
+ }
1268
+ }
1269
+ async function settleWithin(operation, timeoutMs) {
1270
+ let timer;
1271
+ const deadline = new Promise((resolve) => {
1272
+ timer = setTimeout(() => resolve("deadline"), timeoutMs);
1273
+ });
1274
+ try {
1275
+ return await Promise.race([operation, deadline]);
1276
+ }
1277
+ finally {
1278
+ if (timer)
1279
+ clearTimeout(timer);
1280
+ }
1281
+ }
1282
+ function validateHost(host) {
1283
+ if (typeof host !== "string" || host.trim().length === 0 || host.length > 255) {
1284
+ throw new TypeError("HTTP host must be a non-empty string of at most 255 characters");
1285
+ }
1286
+ if (/[^\x21-\x7E]/u.test(host)) {
1287
+ throw new TypeError("HTTP host must contain only visible ASCII characters");
1288
+ }
1289
+ return host;
1290
+ }
1291
+ function validatePort(port) {
1292
+ if (!Number.isInteger(port) || Number(port) < 0 || Number(port) > 65_535) {
1293
+ throw new TypeError("HTTP port must be an integer from 0 through 65535");
1294
+ }
1295
+ return Number(port);
1296
+ }
1297
+ function validateMaxConcurrentRequests(candidate) {
1298
+ if (!Number.isSafeInteger(candidate) ||
1299
+ Number(candidate) < 1 ||
1300
+ Number(candidate) > MAX_CONCURRENT_MCP_REQUESTS) {
1301
+ throw new TypeError(`HTTP maxConcurrentRequests must be an integer from 1 through ${MAX_CONCURRENT_MCP_REQUESTS}`);
1302
+ }
1303
+ return Number(candidate);
1304
+ }
1305
+ function validateMaxConnections(candidate) {
1306
+ if (!Number.isSafeInteger(candidate) ||
1307
+ Number(candidate) < 1 ||
1308
+ Number(candidate) > exports.MAX_HTTP_CONNECTIONS) {
1309
+ throw new TypeError(`HTTP maxConnections must be an integer from 1 through ${exports.MAX_HTTP_CONNECTIONS}`);
1310
+ }
1311
+ return Number(candidate);
1312
+ }
1313
+ function validateGracePeriod(gracePeriodMs) {
1314
+ if (!Number.isSafeInteger(gracePeriodMs) ||
1315
+ Number(gracePeriodMs) < 0 ||
1316
+ Number(gracePeriodMs) > 300_000) {
1317
+ throw new TypeError("HTTP close gracePeriodMs must be an integer from 0 through 300000");
1318
+ }
1319
+ return Number(gracePeriodMs);
1320
+ }
1321
+ //# sourceMappingURL=http-runtime.js.map