@layervai/qurl-mcp 0.4.1 → 0.5.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 (169) hide show
  1. package/README.md +742 -50
  2. package/assets/fonts/NotoSansSC-Regular.ttf +0 -0
  3. package/assets/fonts/OFL.txt +93 -0
  4. package/assets/fonts/README.md +18 -0
  5. package/dist/auth/request-context.d.ts +13 -0
  6. package/dist/auth/request-context.d.ts.map +1 -0
  7. package/dist/auth/request-context.js +21 -0
  8. package/dist/auth/request-context.js.map +1 -0
  9. package/dist/auth/static-bearer.d.ts +12 -0
  10. package/dist/auth/static-bearer.d.ts.map +1 -0
  11. package/dist/auth/static-bearer.js +47 -0
  12. package/dist/auth/static-bearer.js.map +1 -0
  13. package/dist/client.d.ts +1 -1
  14. package/dist/client.d.ts.map +1 -1
  15. package/dist/client.js +15 -4
  16. package/dist/client.js.map +1 -1
  17. package/dist/config.d.ts +98 -0
  18. package/dist/config.d.ts.map +1 -0
  19. package/dist/config.js +543 -0
  20. package/dist/config.js.map +1 -0
  21. package/dist/credential-rate-limit-store.d.ts +38 -0
  22. package/dist/credential-rate-limit-store.d.ts.map +1 -0
  23. package/dist/credential-rate-limit-store.js +135 -0
  24. package/dist/credential-rate-limit-store.js.map +1 -0
  25. package/dist/email-addresses.d.ts +7 -0
  26. package/dist/email-addresses.d.ts.map +1 -0
  27. package/dist/email-addresses.js +36 -0
  28. package/dist/email-addresses.js.map +1 -0
  29. package/dist/email-types.d.ts +33 -0
  30. package/dist/email-types.d.ts.map +1 -0
  31. package/dist/email-types.js +28 -0
  32. package/dist/email-types.js.map +1 -0
  33. package/dist/emf-metrics.d.ts +25 -0
  34. package/dist/emf-metrics.d.ts.map +1 -0
  35. package/dist/emf-metrics.js +87 -0
  36. package/dist/emf-metrics.js.map +1 -0
  37. package/dist/http-config.d.ts +38 -0
  38. package/dist/http-config.d.ts.map +1 -0
  39. package/dist/http-config.js +243 -0
  40. package/dist/http-config.js.map +1 -0
  41. package/dist/http-routes.d.ts +5 -0
  42. package/dist/http-routes.d.ts.map +1 -0
  43. package/dist/http-routes.js +12 -0
  44. package/dist/http-routes.js.map +1 -0
  45. package/dist/http.d.ts +33 -0
  46. package/dist/http.d.ts.map +1 -0
  47. package/dist/http.js +1116 -0
  48. package/dist/http.js.map +1 -0
  49. package/dist/index.d.ts +1 -1
  50. package/dist/index.d.ts.map +1 -1
  51. package/dist/index.js +42 -26
  52. package/dist/index.js.map +1 -1
  53. package/dist/logging.d.ts +7 -0
  54. package/dist/logging.d.ts.map +1 -0
  55. package/dist/logging.js +110 -0
  56. package/dist/logging.js.map +1 -0
  57. package/dist/server.d.ts +12 -4
  58. package/dist/server.d.ts.map +1 -1
  59. package/dist/server.js +33 -8
  60. package/dist/server.js.map +1 -1
  61. package/dist/services/email.d.ts +17 -0
  62. package/dist/services/email.d.ts.map +1 -0
  63. package/dist/services/email.js +351 -0
  64. package/dist/services/email.js.map +1 -0
  65. package/dist/services/html.d.ts +5 -0
  66. package/dist/services/html.d.ts.map +1 -0
  67. package/dist/services/html.js +28 -0
  68. package/dist/services/html.js.map +1 -0
  69. package/dist/services/legal-pages.d.ts +12 -0
  70. package/dist/services/legal-pages.d.ts.map +1 -0
  71. package/dist/services/legal-pages.js +588 -0
  72. package/dist/services/legal-pages.js.map +1 -0
  73. package/dist/services/text-pdf.d.ts +16 -0
  74. package/dist/services/text-pdf.d.ts.map +1 -0
  75. package/dist/services/text-pdf.js +141 -0
  76. package/dist/services/text-pdf.js.map +1 -0
  77. package/dist/services/video-page.d.ts +4 -0
  78. package/dist/services/video-page.d.ts.map +1 -0
  79. package/dist/services/video-page.js +311 -0
  80. package/dist/services/video-page.js.map +1 -0
  81. package/dist/text.d.ts +4 -0
  82. package/dist/text.d.ts.map +1 -0
  83. package/dist/text.js +16 -0
  84. package/dist/text.js.map +1 -0
  85. package/dist/tools/_shared.d.ts +9 -1
  86. package/dist/tools/_shared.d.ts.map +1 -1
  87. package/dist/tools/_shared.js +20 -8
  88. package/dist/tools/_shared.js.map +1 -1
  89. package/dist/tools/batch-create.d.ts +12 -11
  90. package/dist/tools/batch-create.d.ts.map +1 -1
  91. package/dist/tools/batch-create.js +6 -4
  92. package/dist/tools/batch-create.js.map +1 -1
  93. package/dist/tools/create-qurl.d.ts +43 -4
  94. package/dist/tools/create-qurl.d.ts.map +1 -1
  95. package/dist/tools/create-qurl.js +63 -30
  96. package/dist/tools/create-qurl.js.map +1 -1
  97. package/dist/tools/delete-qurl.d.ts +3 -2
  98. package/dist/tools/delete-qurl.d.ts.map +1 -1
  99. package/dist/tools/delete-qurl.js +3 -10
  100. package/dist/tools/delete-qurl.js.map +1 -1
  101. package/dist/tools/email-delivery.d.ts +37 -0
  102. package/dist/tools/email-delivery.d.ts.map +1 -0
  103. package/dist/tools/email-delivery.js +115 -0
  104. package/dist/tools/email-delivery.js.map +1 -0
  105. package/dist/tools/extend-qurl.d.ts +6 -5
  106. package/dist/tools/extend-qurl.d.ts.map +1 -1
  107. package/dist/tools/extend-qurl.js +3 -3
  108. package/dist/tools/extend-qurl.js.map +1 -1
  109. package/dist/tools/get-qurl.d.ts +6 -5
  110. package/dist/tools/get-qurl.d.ts.map +1 -1
  111. package/dist/tools/get-qurl.js +5 -3
  112. package/dist/tools/get-qurl.js.map +1 -1
  113. package/dist/tools/list-qurl-sessions.d.ts +5 -4
  114. package/dist/tools/list-qurl-sessions.d.ts.map +1 -1
  115. package/dist/tools/list-qurl-sessions.js +2 -2
  116. package/dist/tools/list-qurl-sessions.js.map +1 -1
  117. package/dist/tools/list-qurls.d.ts +8 -7
  118. package/dist/tools/list-qurls.d.ts.map +1 -1
  119. package/dist/tools/list-qurls.js +9 -7
  120. package/dist/tools/list-qurls.js.map +1 -1
  121. package/dist/tools/mint-link.d.ts +39 -3
  122. package/dist/tools/mint-link.d.ts.map +1 -1
  123. package/dist/tools/mint-link.js +24 -13
  124. package/dist/tools/mint-link.js.map +1 -1
  125. package/dist/tools/output-schemas.d.ts +102 -45
  126. package/dist/tools/output-schemas.d.ts.map +1 -1
  127. package/dist/tools/output-schemas.js +54 -29
  128. package/dist/tools/output-schemas.js.map +1 -1
  129. package/dist/tools/resolve-qurl.d.ts +4 -3
  130. package/dist/tools/resolve-qurl.d.ts.map +1 -1
  131. package/dist/tools/resolve-qurl.js +3 -3
  132. package/dist/tools/resolve-qurl.js.map +1 -1
  133. package/dist/tools/revoke-qurl-token.d.ts +3 -2
  134. package/dist/tools/revoke-qurl-token.d.ts.map +1 -1
  135. package/dist/tools/revoke-qurl-token.js +2 -2
  136. package/dist/tools/revoke-qurl-token.js.map +1 -1
  137. package/dist/tools/terminate-qurl-sessions.d.ts +3 -2
  138. package/dist/tools/terminate-qurl-sessions.d.ts.map +1 -1
  139. package/dist/tools/terminate-qurl-sessions.js +7 -3
  140. package/dist/tools/terminate-qurl-sessions.js.map +1 -1
  141. package/dist/tools/update-qurl-token.d.ts +5 -4
  142. package/dist/tools/update-qurl-token.d.ts.map +1 -1
  143. package/dist/tools/update-qurl-token.js +2 -2
  144. package/dist/tools/update-qurl-token.js.map +1 -1
  145. package/dist/tools/update-qurl.d.ts +6 -5
  146. package/dist/tools/update-qurl.d.ts.map +1 -1
  147. package/dist/tools/update-qurl.js +4 -4
  148. package/dist/tools/update-qurl.js.map +1 -1
  149. package/dist/tools/upload-file-data-qurl.d.ts +182 -0
  150. package/dist/tools/upload-file-data-qurl.d.ts.map +1 -0
  151. package/dist/tools/upload-file-data-qurl.js +200 -0
  152. package/dist/tools/upload-file-data-qurl.js.map +1 -0
  153. package/dist/tools/upload-file-qurl.d.ts +162 -0
  154. package/dist/tools/upload-file-qurl.d.ts.map +1 -0
  155. package/dist/tools/upload-file-qurl.js +167 -0
  156. package/dist/tools/upload-file-qurl.js.map +1 -0
  157. package/dist/tools/upload-file-shared.d.ts +36 -0
  158. package/dist/tools/upload-file-shared.d.ts.map +1 -0
  159. package/dist/tools/upload-file-shared.js +347 -0
  160. package/dist/tools/upload-file-shared.js.map +1 -0
  161. package/dist/tools/upload-mint-options.d.ts +22 -0
  162. package/dist/tools/upload-mint-options.d.ts.map +1 -0
  163. package/dist/tools/upload-mint-options.js +29 -0
  164. package/dist/tools/upload-mint-options.js.map +1 -0
  165. package/dist/tools/upload-text-qurl.d.ts +144 -0
  166. package/dist/tools/upload-text-qurl.d.ts.map +1 -0
  167. package/dist/tools/upload-text-qurl.js +102 -0
  168. package/dist/tools/upload-text-qurl.js.map +1 -0
  169. package/package.json +25 -7
package/dist/http.js ADDED
@@ -0,0 +1,1116 @@
1
+ #!/usr/bin/env node
2
+ import { isHttpEmailAuthorized } from "./services/email.js";
3
+ import { createHash, randomUUID, timingSafeEqual } from "node:crypto";
4
+ import { createReadStream, existsSync, realpathSync } from "node:fs";
5
+ import { lstat } from "node:fs/promises";
6
+ import { createRequire } from "node:module";
7
+ import { fileURLToPath } from "node:url";
8
+ import { clearSensitiveLogValues, formatErrorForLog, installTimestampedConsole, logInfo, registerSensitiveLogValues, sanitizeLogValue, } from "./logging.js";
9
+ import express from "express";
10
+ import { hostHeaderValidation, localhostHostValidation, } from "@modelcontextprotocol/sdk/server/middleware/hostHeaderValidation.js";
11
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
12
+ import { requireBearerAuth } from "@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js";
13
+ import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
14
+ import { rateLimit } from "express-rate-limit";
15
+ import { runWithRequestAuthContext } from "./auth/request-context.js";
16
+ import { canonicalizeBearerToken, createPassthroughBearerVerifier, createQurlClientFromBearerToken, } from "./auth/static-bearer.js";
17
+ import { DEFAULT_MAX_UPLOAD_FILE_DATA_BYTES, getDefaultConfigPath, inspectSmtpConfig, loadRuntimeConfig, isLoopbackHostname, } from "./config.js";
18
+ import { assertDeployedStatelessRequirements, assertStatelessParserBudget, getDefaultHttpConfigPath, getJsonBodyLimitBytes, loadHttpServerConfig, normalizeMaxConcurrentRequests, normalizeRateLimitDynamoDbTable, } from "./http-config.js";
19
+ import { HEALTH_HTTP_PATH, MCP_HTTP_PATH } from "./http-routes.js";
20
+ import { getLegalDocuments, renderLegalDocumentHtml } from "./services/legal-pages.js";
21
+ import { getPublicVideoFileRoute, renderPublicVideoPageHtml } from "./services/video-page.js";
22
+ import { createServer } from "./server.js";
23
+ import { DynamoDbCredentialRateLimitStore, MemoryCredentialRateLimitStore, } from "./credential-rate-limit-store.js";
24
+ import { McpEmfMetrics, normalizeMcpMetricsIdentity } from "./emf-metrics.js";
25
+ const DISCONNECTED_SESSION_GRACE_MS = 30_000;
26
+ const STATELESS_HEADERS_TIMEOUT_MS = 15_000;
27
+ const STATELESS_REQUEST_TIMEOUT_MS = 120_000;
28
+ const STATELESS_SOCKET_IDLE_TIMEOUT_MS = 120_000;
29
+ function requireRateLimitDynamoDbTable(config) {
30
+ const tableName = normalizeRateLimitDynamoDbTable(config.rateLimitDynamoDbTable);
31
+ if (!tableName) {
32
+ // loadHttpServerConfig enforces this too, but createHttpRuntime is public
33
+ // and can be called directly. Preserve the same fail-fast invariant there.
34
+ throw new Error("rateLimitDynamoDbTable is required for the dynamodb credential store.");
35
+ }
36
+ return tableName;
37
+ }
38
+ function appendStructuredHeader(res, name, value) {
39
+ const existing = res.getHeader(name);
40
+ const fields = existing === undefined ? [] : Array.isArray(existing) ? existing : [existing];
41
+ // Structured fields are one comma-joined field value even when independent
42
+ // policies contribute members. Set one physical header line so clients do
43
+ // not have to normalize duplicate RateLimit/RateLimit-Policy lines.
44
+ res.setHeader(name, [...fields.map(String), value].join(", "));
45
+ }
46
+ export function createHttpRuntime(config, options) {
47
+ const runtimeConfigPath = options.runtimeConfigPath ?? getDefaultConfigPath();
48
+ const version = options.version;
49
+ const port = config.port;
50
+ const host = config.host;
51
+ const baseUrl = config.baseUrl;
52
+ const defaultQurlApiUrl = config.defaultQurlApiUrl;
53
+ const defaultQurlConnectorUrl = config.defaultQurlConnectorUrl;
54
+ const stateless = config.stateless ?? false;
55
+ const maxConcurrentRequests = normalizeMaxConcurrentRequests(config.maxConcurrentRequests);
56
+ assertStatelessParserBudget(stateless, maxConcurrentRequests, config.maxUploadFileDataBytes);
57
+ let inFlightRequests = 0;
58
+ // This public API can bypass loadHttpServerConfig, so both entry points use
59
+ // one normalizer for the complete, trimmed, stateless-only identity contract.
60
+ const metricsIdentity = normalizeMcpMetricsIdentity({
61
+ namespace: config.metricsNamespace,
62
+ service: config.metricsService,
63
+ environment: config.metricsEnvironment,
64
+ }, stateless);
65
+ // Embedders can bypass loadHttpServerConfig, so the runtime seam enforces
66
+ // the same load-bearing non-loopback deployment contract.
67
+ assertDeployedStatelessRequirements(host, stateless, config.credentialRateLimitStore ?? "memory", metricsIdentity);
68
+ const metrics = new McpEmfMetrics(metricsIdentity,
69
+ // Both loader and direct-call validation guarantee a positive denominator.
70
+ () => (inFlightRequests / maxConcurrentRequests) * 100);
71
+ const credentialRateLimitStore = options.credentialRateLimitStore ??
72
+ (config.credentialRateLimitStore === "dynamodb"
73
+ ? new DynamoDbCredentialRateLimitStore(requireRateLimitDynamoDbTable(config))
74
+ : new MemoryCredentialRateLimitStore());
75
+ // Injected stores are an embedding seam and may need initialization even
76
+ // when config names the compatibility memory backend. Require initialize()
77
+ // for every injected implementation; only the module-owned memory store is
78
+ // known to be ready without it.
79
+ let credentialRateLimitStoreInitialized = options.credentialRateLimitStore === undefined &&
80
+ config.credentialRateLimitStore !== "dynamodb";
81
+ // Bound completed-response teardown independently from active parser work.
82
+ // A slow SDK close path can consume at most one additional concurrency pool.
83
+ const closingStatelessRequests = new Set();
84
+ const app = express();
85
+ app.disable("x-powered-by");
86
+ if (config.trustProxyHops > 0) {
87
+ app.set("trust proxy", config.trustProxyHops);
88
+ }
89
+ const mcpRateLimiter = rateLimit({
90
+ windowMs: 60_000,
91
+ limit: config.mcpRateLimitPerMinute,
92
+ // Pin express-rate-limit's IPv6 privacy-address aggregation policy rather
93
+ // than inheriting a library-default change on upgrade.
94
+ ipv6Subnet: 56,
95
+ // `identifier` names the draft-8 RateLimit policy; request IP remains the
96
+ // default key. The credential policy below supplies its own keyGenerator.
97
+ identifier: "ip",
98
+ standardHeaders: "draft-8",
99
+ legacyHeaders: false,
100
+ handler: (_req, res) => rejectJsonRpc(res, 429, "Too many requests."),
101
+ });
102
+ const createPublicRateLimiter = () => rateLimit({
103
+ windowMs: 60_000,
104
+ limit: config.publicFileRateLimitPerMinute,
105
+ ipv6Subnet: 56,
106
+ standardHeaders: "draft-8",
107
+ legacyHeaders: false,
108
+ handler: (_req, res) => {
109
+ res.status(429).send("Too many requests.");
110
+ },
111
+ });
112
+ // Legal documents and the video page share an aggregate browser-page bucket.
113
+ // Video byte-range traffic and health probes use isolated instances so
114
+ // playback and liveness checks cannot starve the public documents.
115
+ const publicRouteRateLimiter = createPublicRateLimiter();
116
+ const videoFileRateLimiter = createPublicRateLimiter();
117
+ const healthRateLimiter = createPublicRateLimiter();
118
+ const bearerAuthMiddleware = requireBearerAuth({
119
+ verifier: createPassthroughBearerVerifier(),
120
+ requiredScopes: ["mcp:tools"],
121
+ });
122
+ const concurrencyLimiter = (_req, res, next) => {
123
+ if (inFlightRequests >= maxConcurrentRequests ||
124
+ closingStatelessRequests.size >= maxConcurrentRequests) {
125
+ // This is an admission-failure metric, not a pure active-work gauge: a
126
+ // saturated teardown backlog is also capacity loss and should page. The
127
+ // autoscaling policy uses McpConcurrencyUtilization alone, so teardown
128
+ // lag cannot spuriously drive scaling from this counter.
129
+ metrics.incrementConcurrencyRejected();
130
+ rejectJsonRpc(res, 503, "The MCP request concurrency limit has been reached.");
131
+ return;
132
+ }
133
+ inFlightRequests += 1;
134
+ metrics.observeConcurrencyUtilization();
135
+ let released = false;
136
+ const release = () => {
137
+ if (released)
138
+ return;
139
+ released = true;
140
+ inFlightRequests -= 1;
141
+ };
142
+ // Release when the response lifetime ends: this permit bounds active body
143
+ // parsing/request work, not asynchronously closing MCP objects. Teardown is
144
+ // tracked separately in closingStatelessRequests and drained on shutdown.
145
+ res.once("finish", release);
146
+ res.once("close", release);
147
+ next();
148
+ };
149
+ const credentialRateLimiter = async (req, res, next) => {
150
+ const token = getAuthenticatedBearerToken(req);
151
+ if (!token) {
152
+ rejectJsonRpc(res, 401, "Bearer authentication required.");
153
+ return;
154
+ }
155
+ try {
156
+ const windowStartedAtMs = Date.now();
157
+ const credentialDigest = digestBearerToken(token).toString("hex");
158
+ const count = await credentialRateLimitStore.increment({
159
+ credentialDigest,
160
+ windowStartedAtMs,
161
+ });
162
+ const remaining = Math.max(0, config.mcpRateLimitPerMinute - count);
163
+ const resetSeconds = Math.max(1, Math.ceil((60_000 - (windowStartedAtMs % 60_000)) / 1_000));
164
+ appendStructuredHeader(res, "RateLimit", `"credential"; r=${remaining}; t=${resetSeconds}`);
165
+ appendStructuredHeader(res, "RateLimit-Policy", `"credential"; q=${config.mcpRateLimitPerMinute}; w=60`);
166
+ if (count > config.mcpRateLimitPerMinute) {
167
+ rejectJsonRpc(res, 429, "Too many requests.");
168
+ return;
169
+ }
170
+ next();
171
+ }
172
+ catch (error) {
173
+ metrics.incrementRateLimitStoreErrors();
174
+ console.error(`[mcp-http] credential rate-limit store failed (${formatErrorForLog(error)})`);
175
+ rejectJsonRpc(res, 503, "Credential rate-limit service is unavailable.");
176
+ }
177
+ };
178
+ // The credential guard and limiter core are one middleware, so a future
179
+ // array reorder cannot make tokenless requests reach the keyed store.
180
+ // Preserve the existing stateful contract: POST, SSE GET, and explicit
181
+ // DELETE all consume the process-local credential quota. Stateless GET and
182
+ // DELETE are unsupported probes and bypass the fleet-wide store below.
183
+ const authenticatedMcpMiddleware = [bearerAuthMiddleware, credentialRateLimiter];
184
+ const authenticatedMcpPostMiddleware = [
185
+ bearerAuthMiddleware,
186
+ ...(stateless ? [concurrencyLimiter] : []),
187
+ credentialRateLimiter,
188
+ ];
189
+ const rejectUnsupportedStatelessMethod = (method) => (_req, res) => {
190
+ res.set("Allow", "POST");
191
+ rejectJsonRpc(res, 405, `${method} is not supported in stateless HTTP mode.`, -32600);
192
+ };
193
+ // Readiness must not depend on the public Host allowlist: ALB probes use the
194
+ // target IP and port as Host. The response carries no state and has no side
195
+ // effects; keep both properties true before expanding this exemption.
196
+ // /healthz is intentionally unauthenticated and Host-unvalidated for every
197
+ // caller, not only ALB-shaped Host values.
198
+ app.get(HEALTH_HTTP_PATH, healthRateLimiter, (_req, res) => {
199
+ res.json({ ok: true });
200
+ });
201
+ if (config.allowedHosts?.length) {
202
+ app.use(hostHeaderValidation(config.allowedHosts));
203
+ }
204
+ else {
205
+ app.use(localhostHostValidation());
206
+ }
207
+ // Host validation may admit aliases for routing, but browser-originated MCP
208
+ // requests intentionally use the single canonical public origin in baseUrl.
209
+ // Do not widen this check merely because allowedHosts contains extra names.
210
+ const allowedOrigin = new URL(baseUrl).origin;
211
+ // This is the complete stateful browser-route set today. Add any future
212
+ // state-changing browser route here rather than assuming this check is global.
213
+ app.use((req, res, next) => {
214
+ if (req.path !== MCP_HTTP_PATH && req.path !== `${MCP_HTTP_PATH}/`) {
215
+ next();
216
+ return;
217
+ }
218
+ const origin = req.headers.origin;
219
+ if (origin === undefined) {
220
+ next();
221
+ return;
222
+ }
223
+ try {
224
+ if (typeof origin === "string" && new URL(origin).origin === allowedOrigin) {
225
+ next();
226
+ return;
227
+ }
228
+ }
229
+ catch {
230
+ // Reject malformed Origin values with the same bounded response.
231
+ }
232
+ res.status(403).send("Origin is not allowed.");
233
+ });
234
+ const parseConfiguredMcpJsonBody = express.json({
235
+ limit: getJsonBodyLimitBytes(config.maxUploadFileDataBytes),
236
+ strict: true,
237
+ });
238
+ const parseUnvalidatedMcpJsonBody = express.json({
239
+ limit: getJsonBodyLimitBytes(Math.min(config.maxUploadFileDataBytes, DEFAULT_MAX_UPLOAD_FILE_DATA_BYTES)),
240
+ strict: true,
241
+ });
242
+ const sessions = new Map();
243
+ const closingSessions = new Map();
244
+ const activeStatelessRequests = new Set();
245
+ let pendingInitializations = 0;
246
+ const pendingInitializationsByCredential = new Map();
247
+ const parseMcpJsonBody = (req, res, next) => {
248
+ const bearerToken = getAuthenticatedBearerToken(req);
249
+ const session = sessions.get(getSessionId(req) ?? "");
250
+ const mayUseConfiguredLimit = stateless ||
251
+ (session?.credentialValidated === true &&
252
+ bearerToken !== undefined &&
253
+ bearerTokenMatches(bearerToken, session.bearerTokenDigest));
254
+ // Session lookup alone is not authorization: in stateful mode the digest
255
+ // re-check prevents a guessed or leaked session ID from unlocking the
256
+ // larger parser ceiling. Stateless mode has no session to validate, so its
257
+ // configured parser ceiling is instead bounded by the permit acquired
258
+ // before parsing. This is a memory-amplification gate, not a qURL scope
259
+ // boundary; each operation still enforces its downstream scopes.
260
+ const locals = res.locals;
261
+ locals.usingUnvalidatedBodyLimit = !mayUseConfiguredLimit;
262
+ const parser = mayUseConfiguredLimit ? parseConfiguredMcpJsonBody : parseUnvalidatedMcpJsonBody;
263
+ parser(req, res, next);
264
+ };
265
+ function markSessionDisconnected(sessionId) {
266
+ if (!sessionId)
267
+ return;
268
+ const session = sessions.get(sessionId);
269
+ if (!session)
270
+ return;
271
+ const disconnectedAt = Date.now();
272
+ session.lastActivityAt = disconnectedAt;
273
+ session.disconnectedAt = disconnectedAt;
274
+ }
275
+ async function closeSession(sessionId) {
276
+ const existingClose = closingSessions.get(sessionId);
277
+ if (existingClose) {
278
+ await existingClose;
279
+ return;
280
+ }
281
+ const session = sessions.get(sessionId);
282
+ if (!session)
283
+ return;
284
+ // Admission replacement relies on removal before the first await.
285
+ sessions.delete(sessionId);
286
+ const closePromise = withRequestAuth(session.sessionId, session.bearerTokenForRedaction, async () => {
287
+ try {
288
+ await session.server.close();
289
+ }
290
+ catch (error) {
291
+ // Format while the credential-scoped redaction context is still active.
292
+ console.error(`[mcp-http] session close failed (${formatErrorForLog(error)})`);
293
+ }
294
+ });
295
+ closingSessions.set(sessionId, closePromise);
296
+ try {
297
+ await closePromise;
298
+ }
299
+ finally {
300
+ closingSessions.delete(sessionId);
301
+ clearSensitiveLogValues(`http-session:${sessionId}`);
302
+ }
303
+ }
304
+ async function sweepExpiredSessions(now = Date.now()) {
305
+ const expiredIds = [...sessions.values()]
306
+ .filter((session) => {
307
+ if (now - session.createdAt >= config.sessionAbsoluteTtlMs) {
308
+ // The absolute lifetime applies even to active tool/SSE requests so
309
+ // keepalives cannot pin a validated session slot indefinitely.
310
+ return true;
311
+ }
312
+ if (session.activeRequests === 0 &&
313
+ session.disconnectedAt !== undefined &&
314
+ now - session.disconnectedAt >=
315
+ // A deliberately shorter configured idle TTL remains authoritative.
316
+ Math.min(DISCONNECTED_SESSION_GRACE_MS, config.sessionIdleTtlMs)) {
317
+ return true;
318
+ }
319
+ if (!session.credentialValidated) {
320
+ // The pending-session window is an absolute validation deadline.
321
+ // Close even an active SSE stream so it cannot hold an unvalidated
322
+ // slot indefinitely.
323
+ return now - session.createdAt >= config.unvalidatedSessionTtlMs;
324
+ }
325
+ return (session.activeRequests === 0 && now - session.lastActivityAt >= config.sessionIdleTtlMs);
326
+ })
327
+ .map((session) => session.sessionId);
328
+ await Promise.all(expiredIds.map((sessionId) => closeSession(sessionId)));
329
+ return expiredIds.length;
330
+ }
331
+ async function closeAllSessions() {
332
+ await Promise.all([...sessions.keys()].map((sessionId) => closeSession(sessionId)));
333
+ // A concurrent DELETE/sweep may have removed its registry entry while its
334
+ // asynchronous server.close() is still settling. Shutdown callers wait for
335
+ // that ownership cleanup too rather than observing an empty registry early.
336
+ await Promise.all([...closingSessions.values()]);
337
+ await Promise.all([...activeStatelessRequests].map((request) => closeStatelessRequest(request)));
338
+ await Promise.all([...closingStatelessRequests]);
339
+ }
340
+ async function closeStatelessRequest(request) {
341
+ if (request.closePromise) {
342
+ await request.closePromise;
343
+ return;
344
+ }
345
+ activeStatelessRequests.delete(request);
346
+ const bearerToken = request.bearerToken;
347
+ const closePromise = withRequestAuth(undefined, bearerToken, async () => {
348
+ try {
349
+ await request.transport.close();
350
+ }
351
+ catch (error) {
352
+ console.error(`[mcp-http] stateless transport close failed (${formatErrorForLog(error)})`);
353
+ }
354
+ try {
355
+ await request.server.close();
356
+ }
357
+ catch (error) {
358
+ console.error(`[mcp-http] stateless server close failed (${formatErrorForLog(error)})`);
359
+ }
360
+ }).finally(() => {
361
+ request.bearerToken = "";
362
+ closingStatelessRequests.delete(closePromise);
363
+ });
364
+ request.closePromise = closePromise;
365
+ closingStatelessRequests.add(closePromise);
366
+ await closePromise;
367
+ }
368
+ async function trackSessionActivity(session, fn) {
369
+ session.lastActivityAt = Date.now();
370
+ session.disconnectedAt = undefined;
371
+ session.activeRequests += 1;
372
+ try {
373
+ return await fn();
374
+ }
375
+ finally {
376
+ session.activeRequests -= 1;
377
+ session.lastActivityAt = Date.now();
378
+ }
379
+ }
380
+ function getActiveSessionCount() {
381
+ return sessions.size;
382
+ }
383
+ function getSessionId(req) {
384
+ const header = req.headers["mcp-session-id"];
385
+ return typeof header === "string" ? header : undefined;
386
+ }
387
+ function formatDurationMs(startedAt) {
388
+ return `${Date.now() - startedAt}ms`;
389
+ }
390
+ function getAuthenticatedBearerToken(req) {
391
+ // Narrow the SDK-installed field locally instead of depending on its
392
+ // ambient Express Request augmentation remaining source-compatible.
393
+ const auth = req.auth;
394
+ if (typeof auth !== "object" || auth === null || !("token" in auth))
395
+ return undefined;
396
+ return typeof auth.token === "string" ? canonicalizeBearerToken(auth.token) : undefined;
397
+ }
398
+ function digestBearerToken(token) {
399
+ return createHash("sha256").update(token, "utf8").digest();
400
+ }
401
+ function bearerTokenMatches(token, expectedDigest) {
402
+ return timingSafeEqual(digestBearerToken(token), expectedDigest);
403
+ }
404
+ function getToolCapabilities(bearerToken) {
405
+ // Upload routing is fixed for this runtime; SMTP configuration can refresh.
406
+ const uploads = Boolean(defaultQurlConnectorUrl);
407
+ try {
408
+ const runtimeConfig = loadRuntimeConfig(runtimeConfigPath);
409
+ return {
410
+ uploads,
411
+ email: Boolean(runtimeConfig.smtp) &&
412
+ isHttpEmailAuthorized(bearerToken, runtimeConfig.qurlApiKey),
413
+ };
414
+ }
415
+ catch (error) {
416
+ // A malformed SMTP edit must not take unrelated MCP tools offline.
417
+ console.error(`Email discovery disabled (${formatErrorForLog(error)})`);
418
+ return { uploads, email: false };
419
+ }
420
+ }
421
+ function getJsonRpcMethod(body) {
422
+ if (!body || typeof body !== "object")
423
+ return undefined;
424
+ return "method" in body && typeof body.method === "string" ? body.method : undefined;
425
+ }
426
+ function containsInitializeRequest(body) {
427
+ return Array.isArray(body)
428
+ ? body.some((message) => isInitializeRequest(message))
429
+ : isInitializeRequest(body);
430
+ }
431
+ function isExclusiveInitializeRequest(body) {
432
+ return Array.isArray(body)
433
+ ? body.length === 1 && isInitializeRequest(body[0])
434
+ : isInitializeRequest(body);
435
+ }
436
+ function containsToolCall(body) {
437
+ const messages = Array.isArray(body) ? body : [body];
438
+ return messages.some((message) => getJsonRpcMethod(message) === "tools/call");
439
+ }
440
+ function rejectJsonRpc(res, statusCode, message, code = -32000) {
441
+ res.statusCode = statusCode;
442
+ res.setHeader("Content-Type", "application/json");
443
+ res.end(JSON.stringify({
444
+ jsonrpc: "2.0",
445
+ error: {
446
+ code,
447
+ message,
448
+ },
449
+ id: null,
450
+ }));
451
+ }
452
+ async function streamPublicVideo(req, res, filePath) {
453
+ setPublicPageSecurityHeaders(res);
454
+ let stats;
455
+ try {
456
+ // Refuse a final-component symlink so a public video path cannot be
457
+ // retargeted to a different local file after operator configuration.
458
+ // Intermediate directory symlinks retain normal resolution because this
459
+ // absolute path is trusted operator config, never request-derived input.
460
+ stats = await lstat(filePath);
461
+ }
462
+ catch (error) {
463
+ console.error(`[public-video] file inspection failed (${formatErrorForLog(error)})`);
464
+ res.status(404).send("Configured video file was not found.");
465
+ return;
466
+ }
467
+ if (stats.isSymbolicLink() || !stats.isFile() || stats.size === 0) {
468
+ res.status(404).send("Configured video file was not found.");
469
+ return;
470
+ }
471
+ // Content-Length is a request-time snapshot. Public media is trusted,
472
+ // operator-owned configuration and should be replaced atomically; if it
473
+ // is truncated in place, the stream error path below destroys the response
474
+ // rather than serving a silently successful partial body.
475
+ const fileSize = stats.size;
476
+ const range = req.headers.range;
477
+ const pipeFile = (start, end) => {
478
+ const stream = options.fileStreamFactory
479
+ ? options.fileStreamFactory(filePath, { start, end })
480
+ : createReadStream(filePath, { start, end });
481
+ const destroyStream = () => stream.destroy();
482
+ res.once("close", destroyStream);
483
+ stream.once("close", () => res.off("close", destroyStream));
484
+ stream.once("error", (error) => {
485
+ console.error(`[public-video] stream failed (${formatErrorForLog(error)})`);
486
+ res.destroy(error);
487
+ });
488
+ stream.pipe(res);
489
+ };
490
+ res.setHeader("Accept-Ranges", "bytes");
491
+ res.setHeader("Content-Type", "video/mp4");
492
+ res.setHeader("Cache-Control", "public, max-age=300");
493
+ res.setHeader("Cross-Origin-Resource-Policy", "same-origin");
494
+ res.vary("Range");
495
+ const rejectRange = () => {
496
+ res.status(416);
497
+ res.setHeader("Content-Range", `bytes */${fileSize}`);
498
+ // Do not let a shared cache retain a malformed/unsatisfiable request's
499
+ // response under the public representation's cache policy.
500
+ res.setHeader("Cache-Control", "no-store");
501
+ res.end();
502
+ };
503
+ if (!range) {
504
+ res.setHeader("Content-Length", fileSize);
505
+ pipeFile();
506
+ return;
507
+ }
508
+ // Single ranges cover browser video playback. RFC 9110 permits a server to
509
+ // reject unsupported multi-range requests, which we answer with 416.
510
+ const match = /^bytes=(\d*)-(\d*)$/.exec(range);
511
+ if (!match) {
512
+ rejectRange();
513
+ return;
514
+ }
515
+ const parsedStart = match[1] ? Number(match[1]) : undefined;
516
+ const parsedEnd = match[2] ? Number(match[2]) : undefined;
517
+ if ((parsedStart === undefined && parsedEnd === undefined) ||
518
+ (parsedStart !== undefined && !Number.isSafeInteger(parsedStart)) ||
519
+ (parsedEnd !== undefined && !Number.isSafeInteger(parsedEnd))) {
520
+ rejectRange();
521
+ return;
522
+ }
523
+ let start = parsedStart ?? 0;
524
+ let end = parsedEnd ?? fileSize - 1;
525
+ if (parsedStart === undefined && parsedEnd !== undefined) {
526
+ start = Math.max(fileSize - parsedEnd, 0);
527
+ end = fileSize - 1;
528
+ }
529
+ else {
530
+ // RFC 9110 treats an explicit last-byte position beyond the selected
531
+ // representation as the representation's final byte.
532
+ end = Math.min(end, fileSize - 1);
533
+ }
534
+ if (start < 0 || end < 0 || start >= fileSize || start > end) {
535
+ rejectRange();
536
+ return;
537
+ }
538
+ const chunkSize = end - start + 1;
539
+ res.status(206);
540
+ res.setHeader("Content-Range", `bytes ${start}-${end}/${fileSize}`);
541
+ res.setHeader("Content-Length", chunkSize);
542
+ pipeFile(start, end);
543
+ }
544
+ const REINITIALIZE_MESSAGE = "Session not found. The MCP server may have restarted. Please re-initialize the MCP connection.";
545
+ function logMissingSession() {
546
+ console.warn("[mcp-http] session missing; client must re-initialize");
547
+ }
548
+ function findAuthorizedSession(req) {
549
+ const sessionId = getSessionId(req);
550
+ const bearerToken = getAuthenticatedBearerToken(req);
551
+ const session = sessions.get(sessionId ?? "");
552
+ if (!session)
553
+ return undefined;
554
+ if (!bearerToken || !bearerTokenMatches(bearerToken, session.bearerTokenDigest)) {
555
+ return undefined;
556
+ }
557
+ return { session, bearerToken };
558
+ }
559
+ function resolveAuthorizedSession(req) {
560
+ const authorizedSession = findAuthorizedSession(req);
561
+ if (!authorizedSession) {
562
+ // Use the same 404 response and operator log for an unknown ID and a
563
+ // credential mismatch, so neither surface becomes a session oracle.
564
+ logMissingSession();
565
+ }
566
+ return authorizedSession;
567
+ }
568
+ function withRequestAuth(sessionId, qurlApiKey, fn) {
569
+ return runWithRequestAuthContext({
570
+ sessionId: sessionId ?? "(none)",
571
+ qurlApiKey,
572
+ qurlConnectorUrl: defaultQurlConnectorUrl,
573
+ maxUploadFileDataBytes: config.maxUploadFileDataBytes,
574
+ markCredentialValidated: sessionId
575
+ ? () => {
576
+ const session = sessions.get(sessionId);
577
+ if (session)
578
+ session.credentialValidated = true;
579
+ }
580
+ : undefined,
581
+ }, fn);
582
+ }
583
+ const handleStatelessMcpPost = async (req, res) => {
584
+ const bearerToken = getAuthenticatedBearerToken(req);
585
+ const startedAt = Date.now();
586
+ const hasToolCall = containsToolCall(req.body);
587
+ if (!bearerToken) {
588
+ rejectJsonRpc(res, 401, "Bearer authentication required.");
589
+ return;
590
+ }
591
+ // Stateless transports deliberately ignore caller-provided affinity.
592
+ delete req.headers["mcp-session-id"];
593
+ const server = createServer(options.clientFactory?.(bearerToken) ??
594
+ createQurlClientFromBearerToken(bearerToken, { qurlApiUrl: defaultQurlApiUrl }), version, "http", config.maxUploadFileDataBytes, getToolCapabilities(bearerToken));
595
+ const transport = options.transportFactory?.(true) ??
596
+ new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
597
+ const request = { server, transport, bearerToken };
598
+ activeStatelessRequests.add(request);
599
+ let cleanupStarted = false;
600
+ const cleanup = () => {
601
+ if (cleanupStarted)
602
+ return;
603
+ cleanupStarted = true;
604
+ void closeStatelessRequest(request);
605
+ };
606
+ res.once("finish", cleanup);
607
+ res.once("close", cleanup);
608
+ try {
609
+ if (hasToolCall)
610
+ logInfo("[mcp-http] stateless tool call started");
611
+ await server.connect(transport);
612
+ await withRequestAuth(undefined, bearerToken, () => transport.handleRequest(req, res, req.body));
613
+ if (hasToolCall) {
614
+ logInfo(`[mcp-http] stateless tool call finished elapsed=${formatDurationMs(startedAt)}`);
615
+ }
616
+ if (res.writableEnded)
617
+ cleanup();
618
+ }
619
+ catch (error) {
620
+ if (hasToolCall) {
621
+ console.error(`[mcp-http] stateless tool call failed elapsed=${formatDurationMs(startedAt)}`);
622
+ }
623
+ console.error(`Error handling stateless MCP POST request (${formatErrorForLog(error)})`);
624
+ if (!res.headersSent)
625
+ rejectJsonRpc(res, 500, "Internal server error.");
626
+ cleanup();
627
+ }
628
+ };
629
+ const handleMcpPost = async (req, res) => {
630
+ const bearerToken = getAuthenticatedBearerToken(req);
631
+ const startedAt = Date.now();
632
+ const hasToolCall = containsToolCall(req.body);
633
+ if (!bearerToken) {
634
+ rejectJsonRpc(res, 401, "Bearer authentication required.");
635
+ return;
636
+ }
637
+ try {
638
+ const containsInitialize = containsInitializeRequest(req.body);
639
+ if (containsInitialize && !isExclusiveInitializeRequest(req.body)) {
640
+ rejectJsonRpc(res, 400, "Initialize must be sent as the only JSON-RPC message.");
641
+ return;
642
+ }
643
+ if (containsInitialize) {
644
+ const bearerTokenDigest = digestBearerToken(bearerToken);
645
+ const credentialKey = bearerTokenDigest.toString("hex");
646
+ await sweepExpiredSessions();
647
+ let oldestIdle;
648
+ let unvalidatedSessionCount = 0;
649
+ let credentialSessionCount = 0;
650
+ for (const session of sessions.values()) {
651
+ if (!session.credentialValidated) {
652
+ unvalidatedSessionCount += 1;
653
+ if (!oldestIdle && session.activeRequests === 0)
654
+ oldestIdle = session;
655
+ }
656
+ if (session.bearerTokenDigest.equals(bearerTokenDigest))
657
+ credentialSessionCount += 1;
658
+ }
659
+ const pendingForCredential = pendingInitializationsByCredential.get(credentialKey) ?? 0;
660
+ if (credentialSessionCount + pendingForCredential >= config.maxSessionsPerCredential) {
661
+ rejectJsonRpc(res, 503, "The per-credential MCP session limit has been reached. Close an existing session or try again later.");
662
+ return;
663
+ }
664
+ if (unvalidatedSessionCount + pendingInitializations >= config.maxUnvalidatedSessions) {
665
+ // Unverified bearers must not reserve every admission slot until TTL.
666
+ // Map insertion order selects the oldest idle, unvalidated session.
667
+ // Bound asynchronous teardown too; never evict active or validated work.
668
+ if (!oldestIdle || closingSessions.size >= config.maxUnvalidatedSessions) {
669
+ rejectJsonRpc(res, 503, "The pending MCP credential-validation limit has been reached. Try again later.");
670
+ return;
671
+ }
672
+ // closeSession removes the entry synchronously before its first await.
673
+ // Reserve its replacement below without yielding to another initializer.
674
+ void closeSession(oldestIdle.sessionId);
675
+ }
676
+ if (sessions.size + pendingInitializations >= config.maxSessions) {
677
+ rejectJsonRpc(res, 503, "The MCP session limit has been reached. Try again later.");
678
+ return;
679
+ }
680
+ // Reserve both a live-session slot and an unvalidated-session slot
681
+ // plus the caller's per-credential slot before the first initialization
682
+ // await. Keep the cap checks through these increments free of await
683
+ // points so concurrent requests cannot overshoot any configured cap.
684
+ pendingInitializations += 1;
685
+ pendingInitializationsByCredential.set(credentialKey, pendingForCredential + 1);
686
+ try {
687
+ // Initialization always creates a fresh session. Discard any supplied
688
+ // session header before handing the request to the MCP transport so a
689
+ // caller cannot use header presence to select a privileged code path.
690
+ delete req.headers["mcp-session-id"];
691
+ const server = createServer(options.clientFactory?.(bearerToken) ??
692
+ createQurlClientFromBearerToken(bearerToken, { qurlApiUrl: defaultQurlApiUrl }), version, "http", config.maxUploadFileDataBytes, getToolCapabilities(bearerToken));
693
+ const transport = options.transportFactory?.() ??
694
+ new StreamableHTTPServerTransport({
695
+ // The SDK's duplicate Host/Origin options are deprecated in
696
+ // favor of external middleware. Our checks run globally before
697
+ // auth, parsing, or any route can reach this transport.
698
+ sessionIdGenerator: () => randomUUID(),
699
+ });
700
+ let closedBeforeRegistration = false;
701
+ transport.onclose = () => {
702
+ if (!transport.sessionId || !sessions.has(transport.sessionId)) {
703
+ closedBeforeRegistration = true;
704
+ return;
705
+ }
706
+ // Some clients/proxies reconnect the GET SSE stream with the same
707
+ // session ID. Deleting the in-memory session record here can cause
708
+ // a subsequent GET /mcp to be rejected as "unknown session" even
709
+ // though the client is attempting a valid reconnect. Explicit DELETE
710
+ // requests still remove sessions from the registry. A short grace
711
+ // period bounds how long a disconnected session remains available.
712
+ markSessionDisconnected(transport.sessionId);
713
+ };
714
+ try {
715
+ await server.connect(transport);
716
+ await withRequestAuth(undefined, bearerToken, () => transport.handleRequest(req, res, req.body));
717
+ }
718
+ catch (error) {
719
+ await server.close().catch((closeError) => {
720
+ console.error(`[mcp-http] initialize cleanup failed (${formatErrorForLog(closeError)})`);
721
+ });
722
+ throw error;
723
+ }
724
+ if (!transport.sessionId || closedBeforeRegistration) {
725
+ console.warn(closedBeforeRegistration
726
+ ? "[mcp-http] initialize transport closed before session registration"
727
+ : "[mcp-http] initialize completed without session id");
728
+ await server.close();
729
+ return;
730
+ }
731
+ const createdAt = Date.now();
732
+ registerSensitiveLogValues(`http-session:${transport.sessionId}`, [bearerToken]);
733
+ sessions.set(transport.sessionId, {
734
+ sessionId: transport.sessionId,
735
+ transport,
736
+ server,
737
+ bearerTokenForRedaction: bearerToken,
738
+ bearerTokenDigest,
739
+ createdAt,
740
+ lastActivityAt: createdAt,
741
+ activeRequests: 0,
742
+ credentialValidated: false,
743
+ });
744
+ logInfo(`[mcp-http] initialize completed elapsed=${formatDurationMs(startedAt)}`);
745
+ return;
746
+ }
747
+ finally {
748
+ pendingInitializations -= 1;
749
+ const remainingForCredential = (pendingInitializationsByCredential.get(credentialKey) ?? 1) - 1;
750
+ if (remainingForCredential === 0) {
751
+ pendingInitializationsByCredential.delete(credentialKey);
752
+ }
753
+ else {
754
+ pendingInitializationsByCredential.set(credentialKey, remainingForCredential);
755
+ }
756
+ }
757
+ }
758
+ const authorizedSession = resolveAuthorizedSession(req);
759
+ if (!authorizedSession) {
760
+ rejectJsonRpc(res, 404, REINITIALIZE_MESSAGE);
761
+ return;
762
+ }
763
+ const { session, bearerToken: sessionBearerToken } = authorizedSession;
764
+ if (hasToolCall)
765
+ logInfo("[mcp-http] tool call started");
766
+ await trackSessionActivity(session, () => withRequestAuth(session.sessionId, sessionBearerToken, () => session.transport.handleRequest(req, res, req.body)));
767
+ if (hasToolCall)
768
+ logInfo(`[mcp-http] tool call finished elapsed=${formatDurationMs(startedAt)}`);
769
+ }
770
+ catch (error) {
771
+ if (hasToolCall) {
772
+ console.error(`[mcp-http] tool call failed elapsed=${formatDurationMs(startedAt)}`);
773
+ }
774
+ console.error(`Error handling MCP POST request (${formatErrorForLog(error)})`);
775
+ if (!res.headersSent) {
776
+ // Keep every unexpected transport failure identical. Branching on a
777
+ // caller-provided session ID or bearer here would reintroduce a
778
+ // session-existence oracle on the error path.
779
+ rejectJsonRpc(res, 500, "Internal server error.");
780
+ }
781
+ }
782
+ };
783
+ app.post(MCP_HTTP_PATH, mcpRateLimiter, ...authenticatedMcpPostMiddleware, parseMcpJsonBody, stateless ? handleStatelessMcpPost : handleMcpPost);
784
+ app.get(MCP_HTTP_PATH,
785
+ // Keep unsupported stateless probes in the cheap per-IP bucket so they
786
+ // cannot flood 405 responses; the credential/DynamoDB limiter is bypassed.
787
+ mcpRateLimiter, ...(stateless ? [rejectUnsupportedStatelessMethod("GET")] : authenticatedMcpMiddleware), async (req, res) => {
788
+ const authorizedSession = resolveAuthorizedSession(req);
789
+ if (!authorizedSession) {
790
+ res.status(404).send(REINITIALIZE_MESSAGE);
791
+ return;
792
+ }
793
+ const { session, bearerToken } = authorizedSession;
794
+ // The SDK transport can remain reusable after its SSE response closes, so
795
+ // track the response lifecycle directly rather than relying only on the
796
+ // transport-level onclose hook.
797
+ res.once("close", () => markSessionDisconnected(session.sessionId));
798
+ try {
799
+ await trackSessionActivity(session, () => withRequestAuth(session.sessionId, bearerToken, () => session.transport.handleRequest(req, res)));
800
+ }
801
+ catch (error) {
802
+ console.error(`Error handling MCP GET request (${formatErrorForLog(error)})`);
803
+ if (!res.headersSent) {
804
+ res.status(500).send("Internal server error.");
805
+ }
806
+ }
807
+ });
808
+ app.delete(MCP_HTTP_PATH,
809
+ // Match GET: rate-limit probes by IP without charging a bearer counter.
810
+ mcpRateLimiter, ...(stateless ? [rejectUnsupportedStatelessMethod("DELETE")] : authenticatedMcpMiddleware), async (req, res) => {
811
+ const authorizedSession = resolveAuthorizedSession(req);
812
+ if (!authorizedSession) {
813
+ res.status(404).send(REINITIALIZE_MESSAGE);
814
+ return;
815
+ }
816
+ const { session, bearerToken } = authorizedSession;
817
+ try {
818
+ logInfo("[mcp-http] closing session");
819
+ session.lastActivityAt = Date.now();
820
+ await withRequestAuth(session.sessionId, bearerToken, () => session.transport.handleRequest(req, res));
821
+ }
822
+ catch (error) {
823
+ console.error(`Error handling MCP DELETE request (${formatErrorForLog(error)})`);
824
+ if (!res.headersSent) {
825
+ res.status(500).send("Internal server error.");
826
+ }
827
+ }
828
+ finally {
829
+ // DELETE is an explicit teardown request. It intentionally closes the
830
+ // transport even if another request is still in flight rather than
831
+ // allowing a long-running tool call to block client-directed cleanup.
832
+ // The SDK handles DELETE by closing the transport first; its Protocol
833
+ // onclose hook then clears the server's transport reference. closeSession
834
+ // removes our registry reference before calling server.close(), making
835
+ // that final ownership cleanup idempotent and safe if SDK behavior changes.
836
+ await closeSession(session.sessionId);
837
+ }
838
+ });
839
+ const jsonBodyErrorHandler = (error, _req, res, next) => {
840
+ if (res.headersSent) {
841
+ next(error);
842
+ return;
843
+ }
844
+ const bodyErrorStatus = typeof error === "object" &&
845
+ error !== null &&
846
+ "status" in error &&
847
+ typeof error.status === "number"
848
+ ? error.status
849
+ : undefined;
850
+ const bodyErrorType = typeof error === "object" &&
851
+ error !== null &&
852
+ "type" in error &&
853
+ typeof error.type === "string"
854
+ ? error.type
855
+ : undefined;
856
+ if (bodyErrorStatus === 413 || bodyErrorType === "entity.too.large") {
857
+ const locals = res.locals;
858
+ rejectJsonRpc(res, 413, locals.usingUnvalidatedBodyLimit &&
859
+ config.maxUploadFileDataBytes > DEFAULT_MAX_UPLOAD_FILE_DATA_BYTES
860
+ ? "Request body is too large for an unvalidated session. Complete a smaller qURL API call first."
861
+ : "Request body is too large.");
862
+ return;
863
+ }
864
+ if (error instanceof SyntaxError) {
865
+ rejectJsonRpc(res, 400, "Request body must be valid JSON.", -32700);
866
+ return;
867
+ }
868
+ if (bodyErrorStatus !== undefined && bodyErrorStatus >= 400 && bodyErrorStatus < 500) {
869
+ rejectJsonRpc(res, bodyErrorStatus, "Request body could not be processed.");
870
+ return;
871
+ }
872
+ console.error(`HTTP middleware failed (${formatErrorForLog(error)})`);
873
+ rejectJsonRpc(res, 500, "Internal server error.");
874
+ };
875
+ function getInlineStyleSources(html) {
876
+ // Page renderers must keep style blocks static. Interpolating request or
877
+ // config data into CSS would make this live-content hash authorize it.
878
+ return [...html.matchAll(/<style[^>]*>([\s\S]*?)<\/style>/gi)].map((match) => `'sha256-${createHash("sha256").update(match[1], "utf8").digest("base64")}'`);
879
+ }
880
+ function setPublicPageSecurityHeaders(res, styleSources = [], allowSameOriginMedia = false) {
881
+ const stylePolicy = styleSources.length > 0 ? styleSources.join(" ") : "'none'";
882
+ const mediaPolicy = allowSameOriginMedia ? "'self'" : "'none'";
883
+ res.set({
884
+ "Content-Security-Policy": `default-src 'none'; style-src ${stylePolicy}; img-src 'none'; media-src ${mediaPolicy}; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`,
885
+ "Referrer-Policy": "no-referrer",
886
+ "X-Content-Type-Options": "nosniff",
887
+ "X-Frame-Options": "DENY",
888
+ });
889
+ }
890
+ const legalDocuments = config.serveLayerVLegalPages ? getLegalDocuments() : [];
891
+ for (const document of legalDocuments) {
892
+ const html = renderLegalDocumentHtml(document.path, baseUrl);
893
+ if (!html)
894
+ continue;
895
+ const styleSources = getInlineStyleSources(html);
896
+ app.get(document.path, publicRouteRateLimiter, (_req, res) => {
897
+ setPublicPageSecurityHeaders(res, styleSources);
898
+ res.type("html").send(html);
899
+ });
900
+ }
901
+ if (config.publicVideo) {
902
+ const publicVideo = config.publicVideo;
903
+ const videoPagePath = publicVideo.pagePath;
904
+ const videoFileRoute = getPublicVideoFileRoute(videoPagePath);
905
+ const videoPageHtml = renderPublicVideoPageHtml(publicVideo, baseUrl);
906
+ const videoStyleSources = getInlineStyleSources(videoPageHtml);
907
+ app.get(videoPagePath, publicRouteRateLimiter, (_req, res) => {
908
+ setPublicPageSecurityHeaders(res, videoStyleSources, true);
909
+ res.type("html").send(videoPageHtml);
910
+ });
911
+ app.get(videoFileRoute, videoFileRateLimiter, async (req, res) => {
912
+ await streamPublicVideo(req, res, publicVideo.filePath);
913
+ });
914
+ }
915
+ // Keep JSON-RPC error envelopes scoped to the protocol route. Public pages
916
+ // use a plain-text fallback so an unrelated handler failure cannot return a
917
+ // misleading JSON-RPC response (or Express's default stack-bearing HTML).
918
+ app.use(MCP_HTTP_PATH, jsonBodyErrorHandler);
919
+ app.use(((error, _req, res, next) => {
920
+ if (res.headersSent) {
921
+ next(error);
922
+ return;
923
+ }
924
+ console.error(`Public HTTP middleware failed (${formatErrorForLog(error)})`);
925
+ res.status(500).type("text").send("Internal server error.");
926
+ }));
927
+ let shutdownHttpServer = () => undefined;
928
+ async function initialize() {
929
+ await credentialRateLimitStore.initialize();
930
+ credentialRateLimitStoreInitialized = true;
931
+ }
932
+ function startHttpServer() {
933
+ if (!credentialRateLimitStoreInitialized) {
934
+ throw new Error("Credential rate-limit store must be initialized before HTTP startup.");
935
+ }
936
+ installTimestampedConsole();
937
+ // Stateless loopback development keeps production interval semantics even
938
+ // without an emitter. Stateful mode cannot configure metric identity and
939
+ // does not schedule an idle heartbeat timer.
940
+ const metricsTimer = stateless
941
+ ? globalThis.setInterval(() => metrics.emitHeartbeat(), 30_000)
942
+ : undefined;
943
+ metricsTimer?.unref();
944
+ if (stateless)
945
+ metrics.emitHeartbeat();
946
+ let sweepInProgress = false;
947
+ const shortestSessionTtlMs = Math.min(config.sessionIdleTtlMs, config.sessionAbsoluteTtlMs, config.unvalidatedSessionTtlMs);
948
+ const sweepTimer = !stateless
949
+ ? globalThis.setInterval(() => {
950
+ if (sweepInProgress)
951
+ return;
952
+ sweepInProgress = true;
953
+ void sweepExpiredSessions()
954
+ .catch((error) => {
955
+ console.error(`[mcp-http] session sweep failed (${formatErrorForLog(error)})`);
956
+ })
957
+ .finally(() => {
958
+ sweepInProgress = false;
959
+ });
960
+ }, Math.min(60_000, Math.max(5_000, Math.floor(shortestSessionTtlMs / 2))))
961
+ : undefined;
962
+ sweepTimer?.unref();
963
+ const httpServer = app.listen(port, host, () => {
964
+ logInfo(`qURL MCP HTTP server listening on ${sanitizeLogValue(host)}:${port}`);
965
+ logInfo("HTTP MCP auth mode: qURL API-key passthrough");
966
+ if (config.maxUploadFileDataBytes > DEFAULT_MAX_UPLOAD_FILE_DATA_BYTES) {
967
+ console.warn(stateless
968
+ ? "Warning: maxUploadFileDataBytes exceeds the default; stateless requests may use the configured parser ceiling before downstream bearer validation. Apply an authenticated edge request-size limit on hostile networks."
969
+ : "Warning: maxUploadFileDataBytes exceeds the default; requests above the default parser ceiling require an already-validated MCP session. Apply an authenticated edge request-size limit on hostile networks.");
970
+ }
971
+ if (stateless &&
972
+ config.credentialRateLimitStore !== "dynamodb" &&
973
+ options.credentialRateLimitStore === undefined) {
974
+ console.warn("Warning: stateless HTTP is using the process-local memory credential quota. This is supported only for single-process loopback development; any load-balanced or multi-replica deployment requires DynamoDB.");
975
+ }
976
+ if (config.trustProxyHops === 0 && !isLoopbackHostname(host)) {
977
+ console.warn("Warning: non-loopback HTTP listener has trustProxyHops=0, which is valid only for direct connections. Clients behind a reverse proxy will share the proxy's rate-limit bucket; set the exact trusted hop count.");
978
+ }
979
+ logInfo("HTTP and runtime config loaded.");
980
+ logInfo(`Public legal pages enabled: ${legalDocuments.length}`);
981
+ if (config.publicVideo) {
982
+ logInfo("Public video page enabled.");
983
+ // The video is an optional public asset, not an MCP readiness
984
+ // dependency. Warn at boot but keep /healthz and MCP available; the
985
+ // request path independently fails closed until the asset is usable.
986
+ void lstat(config.publicVideo.filePath)
987
+ .then((stats) => {
988
+ if (stats.isSymbolicLink() || !stats.isFile()) {
989
+ console.warn("[public-video] configured path is not a regular file at startup");
990
+ }
991
+ else if (stats.size === 0) {
992
+ console.warn("[public-video] configured video file is empty at startup");
993
+ }
994
+ })
995
+ .catch(() => {
996
+ console.warn("[public-video] configured video file is unavailable at startup");
997
+ });
998
+ }
999
+ if (defaultQurlConnectorUrl)
1000
+ logInfo("qURL Connector uploads enabled.");
1001
+ const smtpInspection = inspectSmtpConfig(runtimeConfigPath);
1002
+ logInfo(smtpInspection.enabled
1003
+ ? "SMTP is configured."
1004
+ : `SMTP is not configured. Missing fields: ${smtpInspection.missingFields.join(", ") || "(unknown)"}`);
1005
+ if (smtpInspection.enabled) {
1006
+ logInfo(loadRuntimeConfig(runtimeConfigPath).qurlApiKey
1007
+ ? "HTTP email delivery is restricted to the operator credential."
1008
+ : "HTTP email delivery is disabled: QURL_API_KEY is not configured.");
1009
+ }
1010
+ for (const warning of smtpInspection.securityWarnings)
1011
+ console.warn(`Warning: ${warning}`);
1012
+ if (config.allowedHosts?.length) {
1013
+ logInfo(`Host allowlist enabled with ${config.allowedHosts.length} entries.`);
1014
+ }
1015
+ });
1016
+ if (stateless) {
1017
+ // A permit spans parsing through response completion. Bound slow header,
1018
+ // body, and idle-response sockets so a small set of stalled connections
1019
+ // cannot retain the whole stateless permit pool indefinitely.
1020
+ httpServer.headersTimeout = STATELESS_HEADERS_TIMEOUT_MS;
1021
+ httpServer.requestTimeout = STATELESS_REQUEST_TIMEOUT_MS;
1022
+ httpServer.setTimeout(STATELESS_SOCKET_IDLE_TIMEOUT_MS);
1023
+ }
1024
+ let shuttingDown = false;
1025
+ const removeSignalHandlers = () => {
1026
+ process.removeListener("SIGTERM", handleSigterm);
1027
+ process.removeListener("SIGINT", handleSigint);
1028
+ };
1029
+ const shutdown = (signal) => {
1030
+ if (shuttingDown)
1031
+ return;
1032
+ shuttingDown = true;
1033
+ if (sweepTimer)
1034
+ globalThis.clearInterval(sweepTimer);
1035
+ if (metricsTimer)
1036
+ globalThis.clearInterval(metricsTimer);
1037
+ // Preserve the trailing partial interval before ECS scale-in or a
1038
+ // rolling replacement terminates the process.
1039
+ if (stateless)
1040
+ metrics.emitHeartbeat();
1041
+ removeSignalHandlers();
1042
+ logInfo(`Received ${signal}; draining HTTP connections and MCP sessions.`);
1043
+ const forceCloseTimer = globalThis.setTimeout(() => {
1044
+ httpServer.closeAllConnections();
1045
+ }, 10_000);
1046
+ forceCloseTimer.unref();
1047
+ httpServer.close((error) => {
1048
+ void closeAllSessions().finally(() => {
1049
+ globalThis.clearTimeout(forceCloseTimer);
1050
+ if (error) {
1051
+ console.error(`HTTP server shutdown failed (${formatErrorForLog(error)})`);
1052
+ process.exitCode = 1;
1053
+ }
1054
+ });
1055
+ });
1056
+ };
1057
+ const handleSigterm = () => shutdown("SIGTERM");
1058
+ const handleSigint = () => shutdown("SIGINT");
1059
+ process.once("SIGTERM", handleSigterm);
1060
+ process.once("SIGINT", handleSigint);
1061
+ httpServer.once("close", () => {
1062
+ if (sweepTimer)
1063
+ globalThis.clearInterval(sweepTimer);
1064
+ if (metricsTimer)
1065
+ globalThis.clearInterval(metricsTimer);
1066
+ removeSignalHandlers();
1067
+ });
1068
+ shutdownHttpServer = (signal = "shutdown") => shutdown(signal);
1069
+ return httpServer;
1070
+ }
1071
+ return {
1072
+ // start/close are embedding APIs; the observation, streaming, and sweep
1073
+ // hooks are intentionally exposed as deterministic test seams.
1074
+ app,
1075
+ closeAllSessions,
1076
+ emitMetricsHeartbeat: () => metrics.emitHeartbeat(),
1077
+ getActiveSessionCount,
1078
+ // Stateless-only observation seam; stateful runtimes intentionally report
1079
+ // zero because they do not acquire the pre-parser concurrency permit.
1080
+ getInFlightRequestCount: () => inFlightRequests,
1081
+ initialize,
1082
+ shutdownHttpServer: (signal) => shutdownHttpServer(signal),
1083
+ startHttpServer,
1084
+ streamPublicVideo,
1085
+ sweepExpiredSessions,
1086
+ };
1087
+ }
1088
+ const isMainModule = typeof process.argv[1] === "string" &&
1089
+ existsSync(process.argv[1]) &&
1090
+ realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
1091
+ export async function runHttpMain(start = async () => {
1092
+ const require = createRequire(import.meta.url);
1093
+ const { version } = require("../package.json");
1094
+ const runtimeConfigPath = getDefaultConfigPath();
1095
+ const config = loadHttpServerConfig(getDefaultHttpConfigPath());
1096
+ const runtime = createHttpRuntime(config, { runtimeConfigPath, version });
1097
+ await runtime.initialize();
1098
+ runtime.startHttpServer();
1099
+ }) {
1100
+ const handleStartupError = (error) => {
1101
+ installTimestampedConsole();
1102
+ console.error(`qURL MCP HTTP startup failed (${formatErrorForLog(error)})`);
1103
+ // Startup failed before a server or sweep timer was retained. Preserve
1104
+ // stderr flushing and let the empty event loop terminate with this status.
1105
+ process.exitCode = 1;
1106
+ };
1107
+ try {
1108
+ await start();
1109
+ }
1110
+ catch (error) {
1111
+ handleStartupError(error);
1112
+ }
1113
+ }
1114
+ if (isMainModule)
1115
+ void runHttpMain();
1116
+ //# sourceMappingURL=http.js.map