@abapify/adt-mcp 0.3.6 → 0.4.4

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.
@@ -0,0 +1,1561 @@
1
+ import { a as isMcpDestinationKey, o as isMcpOperationClass, t as createMcpServer } from "./server-Dj44Rgau.mjs";
2
+ import { Buffer as Buffer$1 } from "node:buffer";
3
+ import { randomUUID, timingSafeEqual } from "node:crypto";
4
+ import { readFile } from "node:fs/promises";
5
+ import { join } from "node:path";
6
+ import https from "node:https";
7
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
8
+ import { existsSync, readFileSync } from "node:fs";
9
+ import { homedir } from "node:os";
10
+ import { createRemoteJWKSet, jwtVerify } from "jose";
11
+
12
+ //#region src/lib/session/registry.ts
13
+ const DEFAULT_TTL_MS = 18e5;
14
+ function createSessionRegistry(options = {}) {
15
+ const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
16
+ const sessions = /* @__PURE__ */ new Map();
17
+ let sweepTimer;
18
+ const wrapClose = (close) => {
19
+ let closed = false;
20
+ return async () => {
21
+ if (closed) return;
22
+ closed = true;
23
+ await close();
24
+ };
25
+ };
26
+ const registry = {
27
+ create(mcpSessionId, ctx, close) {
28
+ const now = Date.now();
29
+ const session = {
30
+ mcpSessionId,
31
+ createdAt: now,
32
+ lastUsedAt: now,
33
+ ...ctx,
34
+ close: wrapClose(close)
35
+ };
36
+ sessions.set(mcpSessionId, session);
37
+ return session;
38
+ },
39
+ get(mcpSessionId) {
40
+ return sessions.get(mcpSessionId);
41
+ },
42
+ touch(mcpSessionId) {
43
+ const s = sessions.get(mcpSessionId);
44
+ if (s) s.lastUsedAt = Date.now();
45
+ },
46
+ async delete(mcpSessionId) {
47
+ const s = sessions.get(mcpSessionId);
48
+ if (!s) return;
49
+ sessions.delete(mcpSessionId);
50
+ try {
51
+ await s.close();
52
+ } catch {}
53
+ },
54
+ list() {
55
+ return Array.from(sessions.values());
56
+ },
57
+ async shutdown() {
58
+ if (sweepTimer) {
59
+ clearInterval(sweepTimer);
60
+ sweepTimer = void 0;
61
+ }
62
+ const ids = Array.from(sessions.keys());
63
+ await Promise.allSettled(ids.map((id) => registry.delete(id)));
64
+ }
65
+ };
66
+ if (ttlMs > 0) {
67
+ const interval = options.sweepIntervalMs ?? Math.min(Math.floor(ttlMs / 4), 6e4);
68
+ sweepTimer = setInterval(() => {
69
+ const cutoff = Date.now() - ttlMs;
70
+ for (const s of sessions.values()) if (s.lastUsedAt < cutoff) registry.delete(s.mcpSessionId);
71
+ }, Math.max(1e3, interval));
72
+ sweepTimer.unref?.();
73
+ }
74
+ return registry;
75
+ }
76
+
77
+ //#endregion
78
+ //#region src/lib/http/multi-system.ts
79
+ /**
80
+ * Multi-system configuration loader for adt-mcp HTTP transport.
81
+ *
82
+ * Resolves a logical system id (e.g. `DEV`, `PROD`) to concrete ADT
83
+ * connection parameters. Sources (priority order):
84
+ *
85
+ * 1. `SAP_SYSTEMS_JSON` env var — inline JSON object
86
+ * `{ "DEV": { "baseUrl": "...", "client": "100" }, ... }`
87
+ * 2. `SAP_SYSTEMS_FILE` env var — path to a JSON file (YAML is NOT
88
+ * supported in this wave to avoid adding new runtime deps).
89
+ * 3. `~/.adt/systems.json` — default JSON file (YAML is NOT supported).
90
+ *
91
+ * Missing/empty config yields an empty registry, and `resolve()` returns
92
+ * `undefined` for every id.
93
+ *
94
+ * Security policy: the registry holds ONLY connection metadata
95
+ * (`baseUrl`, `client`). Credentials (`username`, `password`) MUST come
96
+ * from the `sap_connect` tool call at runtime, never from disk. Any
97
+ * `username`/`password` fields present in the JSON are silently dropped
98
+ * with a warning so secrets-in-config mistakes don't leak.
99
+ */
100
+ function parseJsonSafe(raw, source) {
101
+ try {
102
+ const value = JSON.parse(raw);
103
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`expected a JSON object, got ${typeof value}`);
104
+ return value;
105
+ } catch (err) {
106
+ throw new Error(`Failed to parse multi-system config from ${source}: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
107
+ }
108
+ }
109
+ function normalise(raw) {
110
+ const out = {};
111
+ for (const [id, entry] of Object.entries(raw)) {
112
+ if (!entry || typeof entry !== "object") continue;
113
+ if (typeof entry.baseUrl !== "string" || entry.baseUrl.length === 0) continue;
114
+ if (entry.username || entry.password) process.stderr.write(`[multi-system] warning: system '${id}' contains credentials in config; dropping them. Pass credentials via sap_connect at runtime.\n`);
115
+ out[id] = {
116
+ baseUrl: entry.baseUrl,
117
+ client: entry.client
118
+ };
119
+ }
120
+ return out;
121
+ }
122
+ function loadMultiSystemConfig() {
123
+ let raw;
124
+ if (process.env.SAP_SYSTEMS_JSON) raw = parseJsonSafe(process.env.SAP_SYSTEMS_JSON, "SAP_SYSTEMS_JSON");
125
+ else {
126
+ const explicit = process.env.SAP_SYSTEMS_FILE;
127
+ const defaultPath = join(homedir(), ".adt", "systems.json");
128
+ const path = explicit && explicit.length > 0 ? explicit : defaultPath;
129
+ if (existsSync(path)) raw = parseJsonSafe(readFileSync(path, "utf8"), path);
130
+ }
131
+ const systems = raw ? normalise(raw) : {};
132
+ return {
133
+ systems,
134
+ resolve(systemId) {
135
+ const entry = systems[systemId];
136
+ if (!entry) return void 0;
137
+ return {
138
+ baseUrl: entry.baseUrl,
139
+ client: entry.client
140
+ };
141
+ }
142
+ };
143
+ }
144
+
145
+ //#endregion
146
+ //#region src/lib/http/oauth.ts
147
+ /**
148
+ * OAuth 2.1 / OIDC bearer-token validator for the adt-mcp HTTP transport.
149
+ *
150
+ * adt-mcp is an MCP *resource server*, not an authorization server — we
151
+ * only **validate** JWTs issued by an external IdP (Okta, Microsoft Entra
152
+ * ID, AWS Cognito, Keycloak, Auth0, …). We do not issue tokens ourselves.
153
+ *
154
+ * Validation steps (per RFC 7519 + RFC 8725 + OAuth 2.1 Section 5.2):
155
+ * 1. Extract `Authorization: Bearer <jwt>` (caller's responsibility).
156
+ * 2. Fetch the JWKS for the configured `issuer`:
157
+ * - If `jwksUri` is provided, use it directly.
158
+ * - Otherwise discover via `${issuer}/.well-known/openid-configuration`.
159
+ * 3. Verify signature + `iss` + `aud` + `exp`/`nbf` (with clock skew).
160
+ * 4. Optionally enforce `requiredScopes` against the token's
161
+ * `scope` (RFC 8693) or `scp` (Entra ID) claim.
162
+ * 5. Extract a stable user identity from a configurable claim
163
+ * (default chain: `preferred_username` → `email` → `sub`).
164
+ *
165
+ * The validator is stateless from the caller's perspective but internally
166
+ * caches the JWKS (jose's `createRemoteJWKSet`) and the OIDC discovery
167
+ * document for one hour.
168
+ *
169
+ * On failure the validator returns `{ valid: false, error }` — it never
170
+ * throws. Callers translate that into an RFC 6750 401 response.
171
+ */
172
+ const DISCOVERY_TTL_MS = 36e5;
173
+ const discoveryCache = /* @__PURE__ */ new Map();
174
+ function trimTrailingSlash(s) {
175
+ return s.endsWith("/") ? s.slice(0, -1) : s;
176
+ }
177
+ async function fetchDiscovery(issuer) {
178
+ const now = Date.now();
179
+ const cached = discoveryCache.get(issuer);
180
+ if (cached && now - cached.fetchedAt < DISCOVERY_TTL_MS) return cached.doc;
181
+ const url = `${trimTrailingSlash(issuer)}/.well-known/openid-configuration`;
182
+ const res = await fetch(url, { headers: { Accept: "application/json" } });
183
+ if (!res.ok) throw new Error(`OIDC discovery failed for ${issuer}: HTTP ${res.status} ${res.statusText}`);
184
+ const doc = await res.json();
185
+ if (!doc.jwks_uri || typeof doc.jwks_uri !== "string") throw new Error(`OIDC discovery document for ${issuer} is missing jwks_uri`);
186
+ discoveryCache.set(issuer, {
187
+ fetchedAt: now,
188
+ doc
189
+ });
190
+ return doc;
191
+ }
192
+ /**
193
+ * Extract the list of scopes from a token payload. Supports both the
194
+ * OAuth 2.0 `scope` string claim (space-delimited) and the Entra ID
195
+ * `scp` claim (string or array).
196
+ */
197
+ function extractScopes(claims) {
198
+ const scope = claims["scope"];
199
+ const scp = claims["scp"];
200
+ const parts = [];
201
+ if (typeof scope === "string") parts.push(...scope.split(" ").map((s) => s.trim()).filter((s) => s.length > 0));
202
+ if (typeof scp === "string") parts.push(...scp.split(" ").map((s) => s.trim()).filter((s) => s.length > 0));
203
+ else if (Array.isArray(scp)) {
204
+ for (const v of scp) if (typeof v === "string" && v.length > 0) parts.push(v);
205
+ }
206
+ return parts;
207
+ }
208
+ function extractUserHint(claims, userClaim, emailClaim, groupsClaim) {
209
+ const record = claims;
210
+ let user;
211
+ if (userClaim) {
212
+ const v = record[userClaim];
213
+ if (typeof v === "string" && v.length > 0) user = v;
214
+ }
215
+ if (!user) for (const c of [
216
+ "preferred_username",
217
+ "email",
218
+ "sub"
219
+ ]) {
220
+ const v = record[c];
221
+ if (typeof v === "string" && v.length > 0) {
222
+ user = v;
223
+ break;
224
+ }
225
+ }
226
+ if (!user) return void 0;
227
+ const emailRaw = record[emailClaim];
228
+ const email = typeof emailRaw === "string" ? emailRaw : void 0;
229
+ const groupsRaw = record[groupsClaim];
230
+ let groups;
231
+ if (Array.isArray(groupsRaw)) groups = groupsRaw.filter((v) => typeof v === "string");
232
+ else if (typeof groupsRaw === "string" && groupsRaw.length > 0) groups = groupsRaw.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
233
+ return {
234
+ user,
235
+ email,
236
+ groups
237
+ };
238
+ }
239
+ /**
240
+ * Build an OAuth/JWT validator for the configured issuer. Throws
241
+ * synchronously on invalid options (e.g. missing issuer).
242
+ */
243
+ function createOAuthValidator(opts) {
244
+ if (!opts.issuer || opts.issuer.length === 0) throw new Error("createOAuthValidator: `issuer` is required");
245
+ const issuer = opts.issuer;
246
+ const audience = opts.audience;
247
+ const requiredScopes = opts.requiredScopes ?? [];
248
+ const clockTolerance = opts.clockTolerance ?? 5;
249
+ const userClaim = opts.userClaim;
250
+ const emailClaim = opts.emailClaim ?? "email";
251
+ const groupsClaim = opts.groupsClaim ?? "groups";
252
+ let staticJwks;
253
+ if (opts.jwksUri) staticJwks = createRemoteJWKSet(new URL(opts.jwksUri));
254
+ const resolvedJwks = /* @__PURE__ */ new Map();
255
+ async function getJwks() {
256
+ if (staticJwks) return staticJwks;
257
+ const uri = (await fetchDiscovery(issuer)).jwks_uri;
258
+ let jwks = resolvedJwks.get(uri);
259
+ if (!jwks) {
260
+ jwks = createRemoteJWKSet(new URL(uri));
261
+ resolvedJwks.set(uri, jwks);
262
+ }
263
+ return jwks;
264
+ }
265
+ return async (token) => {
266
+ if (!token || token.length === 0) return {
267
+ valid: false,
268
+ error: "missing_token"
269
+ };
270
+ let jwks;
271
+ try {
272
+ jwks = await getJwks();
273
+ } catch (err) {
274
+ return {
275
+ valid: false,
276
+ error: `discovery_failed: ${err instanceof Error ? err.message : String(err)}`
277
+ };
278
+ }
279
+ let payload;
280
+ try {
281
+ payload = (await jwtVerify(token, jwks, {
282
+ issuer,
283
+ audience,
284
+ clockTolerance
285
+ })).payload;
286
+ } catch (err) {
287
+ return {
288
+ valid: false,
289
+ error: `invalid_token: ${err instanceof Error ? err.message : String(err)}`
290
+ };
291
+ }
292
+ if (requiredScopes.length > 0) {
293
+ const scopes = new Set(extractScopes(payload));
294
+ const missing = requiredScopes.filter((s) => !scopes.has(s));
295
+ if (missing.length > 0) return {
296
+ valid: false,
297
+ claims: payload,
298
+ error: `insufficient_scope: missing ${missing.join(", ")}`
299
+ };
300
+ }
301
+ const userHint = extractUserHint(payload, userClaim, emailClaim, groupsClaim);
302
+ return {
303
+ valid: true,
304
+ claims: payload,
305
+ userHint
306
+ };
307
+ };
308
+ }
309
+
310
+ //#endregion
311
+ //#region src/lib/http/auth.ts
312
+ function writeUnauthorized(res, oauthError) {
313
+ if (res.headersSent) {
314
+ try {
315
+ res.end();
316
+ } catch {}
317
+ return;
318
+ }
319
+ const challenge = oauthError ? `Bearer realm="adt-mcp", error="${oauthError.split(":")[0].trim()}", error_description="${oauthError.replaceAll("\"", "'")}"` : "Bearer realm=\"adt-mcp\"";
320
+ res.writeHead(401, {
321
+ "Content-Type": "application/json",
322
+ "WWW-Authenticate": challenge
323
+ });
324
+ res.end(JSON.stringify({ error: oauthError ?? "unauthorized" }));
325
+ }
326
+ function constantTimeEqualString(a, b) {
327
+ const ab = Buffer$1.from(a, "utf8");
328
+ const bb = Buffer$1.from(b, "utf8");
329
+ const len = Math.max(ab.length, bb.length);
330
+ const ap = Buffer$1.alloc(len);
331
+ const bp = Buffer$1.alloc(len);
332
+ ab.copy(ap);
333
+ bb.copy(bp);
334
+ return timingSafeEqual(ap, bp) && ab.length === bb.length;
335
+ }
336
+ function extractBearer(req) {
337
+ const h = req.headers["authorization"];
338
+ const value = Array.isArray(h) ? h[0] : h;
339
+ if (!value) return void 0;
340
+ const trimmed = value.trim();
341
+ if (trimmed.length < 7) return void 0;
342
+ if (trimmed.slice(0, 6).toLowerCase() !== "bearer") return void 0;
343
+ const rest = trimmed.slice(6);
344
+ if (rest.length === 0) return void 0;
345
+ const first = rest.charCodeAt(0);
346
+ if (!(first === 32 || first === 9 || first === 10 || first === 13 || first === 11 || first === 12)) return void 0;
347
+ const token = rest.trimStart();
348
+ return token.length > 0 ? token : void 0;
349
+ }
350
+ function headerString(req, name) {
351
+ const raw = req.headers[name.toLowerCase()];
352
+ if (!raw) return void 0;
353
+ const trimmed = (Array.isArray(raw) ? raw[0] : raw)?.trim();
354
+ return trimmed && trimmed.length > 0 ? trimmed : void 0;
355
+ }
356
+ /**
357
+ * Build the auth middleware for the configured mode. Throws at creation
358
+ * time for misconfiguration (e.g. `bearer` mode with no token).
359
+ */
360
+ function createAuthMiddleware(options) {
361
+ if (options.mode === "bearer") {
362
+ if (!options.token || options.token.length === 0) throw new Error("createAuthMiddleware: bearer mode requires a non-empty token");
363
+ const expected = options.token;
364
+ return (req, res) => {
365
+ const presented = extractBearer(req);
366
+ if (!presented || !constantTimeEqualString(presented, expected)) {
367
+ writeUnauthorized(res);
368
+ return { allowed: false };
369
+ }
370
+ return { allowed: true };
371
+ };
372
+ }
373
+ if (options.mode === "proxy") return (req, res) => {
374
+ const user = headerString(req, "x-forwarded-user");
375
+ if (!user) {
376
+ writeUnauthorized(res);
377
+ return { allowed: false };
378
+ }
379
+ const email = headerString(req, "x-forwarded-email");
380
+ const groupsRaw = headerString(req, "x-forwarded-groups");
381
+ return {
382
+ allowed: true,
383
+ userHint: {
384
+ user,
385
+ email,
386
+ groups: groupsRaw ? groupsRaw.split(",").map((s) => s.trim()).filter((s) => s.length > 0) : void 0
387
+ }
388
+ };
389
+ };
390
+ if (options.mode === "oauth") {
391
+ if (!options.oauth) throw new Error("createAuthMiddleware: oauth mode requires an `oauth` option");
392
+ const validator = createOAuthValidator(options.oauth);
393
+ const onUserHint = options.onUserHint;
394
+ return async (req, res) => {
395
+ const presented = extractBearer(req);
396
+ if (!presented) {
397
+ writeUnauthorized(res, "invalid_token: missing bearer token");
398
+ return { allowed: false };
399
+ }
400
+ const result = await validator(presented);
401
+ if (!result.valid) {
402
+ writeUnauthorized(res, result.error ?? "invalid_token");
403
+ return { allowed: false };
404
+ }
405
+ if (onUserHint) onUserHint(result.userHint);
406
+ return {
407
+ allowed: true,
408
+ userHint: result.userHint
409
+ };
410
+ };
411
+ }
412
+ if (options.mode === "invocation") {
413
+ if (!options.invocationVerifier) throw new Error("createAuthMiddleware: invocation mode requires an invocation verifier");
414
+ const verifier = options.invocationVerifier;
415
+ return async (req, res) => {
416
+ const invocation = await verifier.verify(req.headers.authorization);
417
+ if (!invocation) {
418
+ writeUnauthorized(res, "invalid_token");
419
+ return { allowed: false };
420
+ }
421
+ return {
422
+ allowed: true,
423
+ invocation
424
+ };
425
+ };
426
+ }
427
+ return () => ({ allowed: true });
428
+ }
429
+
430
+ //#endregion
431
+ //#region src/lib/http/invocation.ts
432
+ const INVOCATION_VERSION = 1;
433
+ const MAX_IDENTIFIER_LENGTH = 256;
434
+ const MAX_COMPONENT_IDENTIFIER_LENGTH = 512;
435
+ const MAX_JSON_DEPTH = 8;
436
+ const MAX_TOKEN_LIFETIME_SECONDS = 300;
437
+ const MAX_FROZEN_SOURCES = 500;
438
+ const MAX_SOURCE_REFERENCE_LENGTH = 8192;
439
+ const MAX_FROZEN_SOURCE_BYTES = 2097152;
440
+ const MAX_SCOPED_OBJECT_KEYS = 100;
441
+ const MAX_SCOPED_TOOL_CALLS = 12;
442
+ const MAX_SAFE_EXECUTE_GRANT_BYTES = 16384;
443
+ const destinationKeyPattern = /^[a-z][a-z0-9-]{1,62}$/u;
444
+ const canonicalKeyPattern = /^[A-Z0-9_]+:.+$/u;
445
+ const scopedCanonicalObjectKeyPattern = /^[A-Z0-9_]{2,30}:[A-Z0-9_/$-]{1,128}$/u;
446
+ const compactJwsPattern = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/u;
447
+ const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;
448
+ const trustedAgentIds = /* @__PURE__ */ new Set([
449
+ "ai-review",
450
+ "system-assistant",
451
+ "autonomous-review-agent",
452
+ "adt-execution",
453
+ "delegated-assistant"
454
+ ]);
455
+ const trustedOperationClasses = /* @__PURE__ */ new Set([
456
+ "server",
457
+ "read",
458
+ "safe_execute"
459
+ ]);
460
+ const scopedReadTools = /* @__PURE__ */ new Set(["get_object", "get_object_structure"]);
461
+ /**
462
+ * Reports whether this sidecar version can enforce every narrowing claim for
463
+ * an invocation. Unsupported policies deliberately receive no MCP tool
464
+ * access; accepting a syntactically valid policy without enforcing it would
465
+ * widen the signed credential.
466
+ *
467
+ * Every admitted policy has an exact parser. Structurally incomplete or
468
+ * unknown policies fail closed.
469
+ */
470
+ function isSystemAssistantPolicySupported(claims) {
471
+ if (!hasServerReadClasses(claims) || Object.keys(claims.limits).length !== 0) return false;
472
+ const constraintKeys = Object.keys(claims.constraint);
473
+ return constraintKeys.length === 1 && constraintKeys[0] === "systemSid" && requiredIdentifier(claims.constraint.systemSid) !== void 0;
474
+ }
475
+ function hasServerReadClasses(claims) {
476
+ return claims.classes.length === 2 && claims.classes.includes("server") && claims.classes.includes("read");
477
+ }
478
+ function parseDelegatedAssistantReadPolicy(claims) {
479
+ if (claims.agentId !== "delegated-assistant" || claims.destinationKeys.length !== 1 || !hasServerReadClasses(claims) || Object.keys(claims.limits).length !== 0 || !hasExactSortedKeys(claims.constraint, [
480
+ "kind",
481
+ "threadId",
482
+ "executionId",
483
+ "systemSid"
484
+ ]) || claims.constraint.kind !== "delegated-assistant-read-v1") return;
485
+ const threadId = requiredUuid(claims.constraint.threadId);
486
+ const executionId = requiredUuid(claims.constraint.executionId);
487
+ const systemSid = requiredSystemSid(claims.constraint.systemSid);
488
+ if (!threadId || !executionId || !systemSid) return void 0;
489
+ return Object.freeze({
490
+ threadId,
491
+ executionId,
492
+ systemSid
493
+ });
494
+ }
495
+ function isMcpInvocationDispatchPolicySupported(claims) {
496
+ if (claims.agentId === "system-assistant") return isSystemAssistantPolicySupported(claims);
497
+ if (claims.agentId === "autonomous-review-agent") return hasServerReadClasses(claims) && claims.destinationKeys.length === 1 && parseAutonomousReviewAgentPolicy(claims) !== void 0;
498
+ if (claims.agentId === "adt-execution") return parseScopedAdtInvocationPolicy(claims) !== void 0;
499
+ if (claims.agentId === "delegated-assistant") return parseDelegatedAssistantReadPolicy(claims) !== void 0;
500
+ if (claims.agentId === "ai-review") return hasServerReadClasses(claims) && claims.destinationKeys.length === 1 && parseAiReviewFrozenSourcePolicy(claims) !== void 0;
501
+ return false;
502
+ }
503
+ /**
504
+ * The autonomous agent may inspect exactly one System through exactly one
505
+ * Destination. Its execution id binds every ADT activity to ADT's durable
506
+ * Agent Execution, while the sidecar's ordinary scope catalogue continues to
507
+ * deny write tools. No ambient limits or additional constraints are accepted.
508
+ */
509
+ function parseAutonomousReviewAgentPolicy(claims) {
510
+ if (claims.agentId !== "autonomous-review-agent") return void 0;
511
+ if (Object.keys(claims.limits).length !== 0) return void 0;
512
+ const constraintKeys = Object.keys(claims.constraint).sort((a, b) => a.localeCompare(b));
513
+ if (constraintKeys.length !== 2) return void 0;
514
+ if (constraintKeys[0] !== "executionId") return void 0;
515
+ if (constraintKeys[1] !== "systemSid") return void 0;
516
+ const executionId = requiredUuid(claims.constraint.executionId);
517
+ const systemSid = requiredSystemSid(claims.constraint.systemSid);
518
+ if (!executionId || !systemSid) return void 0;
519
+ return Object.freeze({
520
+ executionId,
521
+ systemSid
522
+ });
523
+ }
524
+ function requiredUuid(value) {
525
+ return typeof value === "string" && uuidPattern.test(value) ? value : void 0;
526
+ }
527
+ function requiredSourceReference(value) {
528
+ return requiredString(value, { maxLength: MAX_SOURCE_REFERENCE_LENGTH });
529
+ }
530
+ function hasExactSortedKeys(value, expected) {
531
+ const actual = Object.keys(value).sort((left, right) => left.localeCompare(right));
532
+ const sortedExpected = [...expected].sort((left, right) => left.localeCompare(right));
533
+ return actual.length === sortedExpected.length && actual.every((key, index) => key === sortedExpected[index]);
534
+ }
535
+ function positiveSafeInteger(value) {
536
+ return Number.isSafeInteger(value) && value > 0 ? value : void 0;
537
+ }
538
+ function parseSafeExecuteCommon(value) {
539
+ const maxDurationMs = positiveSafeInteger(value.maxDurationMs);
540
+ const maxResultBytes = positiveSafeInteger(value.maxResultBytes);
541
+ const maxFindings = positiveSafeInteger(value.maxFindings);
542
+ const maxObjects = positiveSafeInteger(value.maxObjects);
543
+ if (maxDurationMs === void 0 || maxResultBytes === void 0 || maxFindings === void 0 || maxObjects === void 0) return;
544
+ return {
545
+ maxDurationMs,
546
+ maxResultBytes,
547
+ maxFindings,
548
+ maxObjects
549
+ };
550
+ }
551
+ const safeExecuteCommonKeys = [
552
+ "operationId",
553
+ "check",
554
+ "maxDurationMs",
555
+ "maxResultBytes",
556
+ "maxFindings",
557
+ "maxObjects"
558
+ ];
559
+ function parseAtcSafeExecutePolicy(cloned, common) {
560
+ if (!common) return void 0;
561
+ if (cloned.operationId !== "atc_run" || cloned.check !== "atc" || !hasExactSortedKeys(cloned, [
562
+ ...safeExecuteCommonKeys,
563
+ "maxPackages",
564
+ "maxVariants"
565
+ ])) return;
566
+ const maxPackages = positiveSafeInteger(cloned.maxPackages);
567
+ const maxVariants = positiveSafeInteger(cloned.maxVariants);
568
+ if (maxPackages === void 0 || maxVariants === void 0) return;
569
+ return Object.freeze({
570
+ operationId: "atc_run",
571
+ check: "atc",
572
+ ...common,
573
+ maxPackages,
574
+ maxVariants
575
+ });
576
+ }
577
+ function parseAunitSafeExecutePolicy(cloned, common) {
578
+ if (!common) return void 0;
579
+ if (cloned.operationId !== "run_unit_tests" || cloned.check !== "aunit" || cloned.effectiveWithCoverage !== false || cloned.effectiveCoverageFormat !== null || !hasExactSortedKeys(cloned, [
580
+ ...safeExecuteCommonKeys,
581
+ "effectiveWithCoverage",
582
+ "effectiveCoverageFormat",
583
+ "maxTestClasses",
584
+ "maxTestMethods"
585
+ ])) return;
586
+ const maxTestClasses = positiveSafeInteger(cloned.maxTestClasses);
587
+ const maxTestMethods = positiveSafeInteger(cloned.maxTestMethods);
588
+ if (maxTestClasses === void 0 || maxTestMethods === void 0) return;
589
+ return Object.freeze({
590
+ operationId: "run_unit_tests",
591
+ check: "aunit",
592
+ effectiveWithCoverage: false,
593
+ effectiveCoverageFormat: null,
594
+ ...common,
595
+ maxTestClasses,
596
+ maxTestMethods
597
+ });
598
+ }
599
+ function parseCoverageSafeExecutePolicy(cloned, common) {
600
+ if (!common) return void 0;
601
+ const format = cloned.effectiveCoverageFormat;
602
+ if (cloned.operationId !== "run_unit_tests" || cloned.check !== "coverage" || cloned.effectiveWithCoverage !== true || format !== "jacoco" && format !== "sonar-generic" || !hasExactSortedKeys(cloned, [
603
+ ...safeExecuteCommonKeys,
604
+ "effectiveWithCoverage",
605
+ "effectiveCoverageFormat",
606
+ "maxPrograms",
607
+ "maxMeasurements"
608
+ ])) return;
609
+ const maxPrograms = positiveSafeInteger(cloned.maxPrograms);
610
+ const maxMeasurements = positiveSafeInteger(cloned.maxMeasurements);
611
+ if (maxPrograms === void 0 || maxMeasurements === void 0) return;
612
+ return Object.freeze({
613
+ operationId: "run_unit_tests",
614
+ check: "coverage",
615
+ effectiveWithCoverage: true,
616
+ effectiveCoverageFormat: format,
617
+ ...common,
618
+ maxPrograms,
619
+ maxMeasurements
620
+ });
621
+ }
622
+ function parseSafeExecutePolicy(value) {
623
+ if (!isPlainObject(value)) return void 0;
624
+ const cloned = cloneJsonRecord(value);
625
+ if (!cloned) return void 0;
626
+ const common = parseSafeExecuteCommon(cloned);
627
+ return parseAtcSafeExecutePolicy(cloned, common) ?? parseAunitSafeExecutePolicy(cloned, common) ?? parseCoverageSafeExecutePolicy(cloned, common);
628
+ }
629
+ function parseSortedUniqueStrings(value, options) {
630
+ if (!Array.isArray(value) || value.length < options.minItems || value.length > options.maxItems) return;
631
+ const parsed = [];
632
+ for (const item of value) {
633
+ if (typeof item !== "string" || !options.matches(item) || parsed.includes(item)) return;
634
+ parsed.push(item);
635
+ }
636
+ const sorted = [...parsed].sort((left, right) => left.localeCompare(right));
637
+ if (!parsed.every((item, index) => item === sorted[index])) return void 0;
638
+ return Object.freeze(parsed);
639
+ }
640
+ function parseScopedObjectKeys(value) {
641
+ return parseSortedUniqueStrings(value, {
642
+ maxItems: MAX_SCOPED_OBJECT_KEYS,
643
+ minItems: 1,
644
+ matches: (item) => scopedCanonicalObjectKeyPattern.test(item)
645
+ });
646
+ }
647
+ function parseScopedToolNames(value, operationClass, safeExecutePolicy) {
648
+ const toolNames = parseSortedUniqueStrings(value, {
649
+ maxItems: operationClass === "read" ? scopedReadTools.size : 1,
650
+ minItems: 1,
651
+ matches: (item) => operationClass === "read" ? scopedReadTools.has(item) : item === "atc_run" || item === "run_unit_tests"
652
+ });
653
+ if (!toolNames) return void 0;
654
+ if (operationClass === "read") return safeExecutePolicy === void 0 ? toolNames : void 0;
655
+ return safeExecutePolicy && toolNames[0] === safeExecutePolicy.operationId ? toolNames : void 0;
656
+ }
657
+ function parseExecutionAuthorizationToken(value) {
658
+ return typeof value === "string" && value.length <= MAX_SAFE_EXECUTE_GRANT_BYTES && compactJwsPattern.test(value) ? value : void 0;
659
+ }
660
+ function parseScopedAdtInvocationPolicy(claims) {
661
+ if (claims.agentId !== "adt-execution" || claims.destinationKeys.length !== 1) return;
662
+ if (claims.classes.length !== 2 || claims.classes[0] !== "server" || claims.classes[1] !== "read" && claims.classes[1] !== "safe_execute") return;
663
+ const operationClass = claims.classes[1];
664
+ const safeExecute = operationClass === "safe_execute";
665
+ const expectedConstraintKeys = [
666
+ "kind",
667
+ "scopeId",
668
+ "executionId",
669
+ "systemSid",
670
+ "resourceKeys",
671
+ "toolNames",
672
+ ...safeExecute ? [
673
+ "safeExecutePolicy",
674
+ "authorizationId",
675
+ "authorizationToken"
676
+ ] : []
677
+ ];
678
+ if (!hasExactSortedKeys(claims.constraint, expectedConstraintKeys)) return;
679
+ if (claims.constraint.kind !== "adt-execution-v1" || !hasExactSortedKeys(claims.limits, ["maxToolCalls"])) return;
680
+ const scopeId = requiredUuid(claims.constraint.scopeId);
681
+ const executionId = requiredUuid(claims.constraint.executionId);
682
+ const systemSid = requiredSystemSid(claims.constraint.systemSid);
683
+ const resourceKeys = parseScopedObjectKeys(claims.constraint.resourceKeys);
684
+ const maxToolCalls = positiveSafeInteger(claims.limits.maxToolCalls);
685
+ if (!scopeId || !executionId || !systemSid || !resourceKeys || maxToolCalls === void 0 || maxToolCalls > MAX_SCOPED_TOOL_CALLS) return;
686
+ const safeExecutePolicy = safeExecute ? parseSafeExecutePolicy(claims.constraint.safeExecutePolicy) : void 0;
687
+ const toolNames = parseScopedToolNames(claims.constraint.toolNames, operationClass, safeExecutePolicy);
688
+ if (!toolNames) return void 0;
689
+ if (!safeExecute) return Object.freeze({
690
+ scopeId,
691
+ executionId,
692
+ systemSid,
693
+ resourceKeys,
694
+ toolNames,
695
+ operationClass,
696
+ maxToolCalls
697
+ });
698
+ const authorizationId = requiredUuid(claims.constraint.authorizationId);
699
+ const authorizationToken = parseExecutionAuthorizationToken(claims.constraint.authorizationToken);
700
+ if (!safeExecutePolicy || !authorizationId || !authorizationToken) return;
701
+ return Object.freeze({
702
+ scopeId,
703
+ executionId,
704
+ systemSid,
705
+ resourceKeys,
706
+ toolNames,
707
+ operationClass,
708
+ maxToolCalls,
709
+ safeExecutePolicy,
710
+ authorizationId,
711
+ authorizationToken
712
+ });
713
+ }
714
+ function parseFrozenSource(source, sourceKeys, sourceRefs) {
715
+ if (!isPlainObject(source)) return void 0;
716
+ const canonicalKey = source.canonicalKey;
717
+ const componentId = requiredComponentIdentifier(source.componentId);
718
+ const sourceRef = requiredSourceReference(source.sourceRef);
719
+ if (typeof canonicalKey !== "string") return void 0;
720
+ if (!canonicalKeyPattern.test(canonicalKey)) return void 0;
721
+ if (!componentId || !sourceRef) return void 0;
722
+ const key = `${canonicalKey}\u0000${componentId}`;
723
+ if (sourceKeys.has(key) || sourceRefs.has(sourceRef)) return void 0;
724
+ sourceKeys.add(key);
725
+ sourceRefs.add(sourceRef);
726
+ return Object.freeze({
727
+ canonicalKey,
728
+ componentId,
729
+ sourceRef
730
+ });
731
+ }
732
+ /**
733
+ * Parse the only AI Review policy currently safe to dispatch. Every property
734
+ * is deliberately exact: accepting a valid JWS with one ignored narrowing
735
+ * field would widen the Review beyond its frozen materialisation.
736
+ */
737
+ const expectedAiReviewConstraintKeys = [
738
+ "frozenSources",
739
+ "kind",
740
+ "reviewId",
741
+ "runId",
742
+ "systemSid"
743
+ ];
744
+ function isSortedKeysEqual(keys, expected) {
745
+ return keys.length === expected.length && keys.every((key, index) => key === expected[index]);
746
+ }
747
+ function parseAiReviewSources(rawSources) {
748
+ if (!Array.isArray(rawSources)) return void 0;
749
+ if (rawSources.length === 0 || rawSources.length > MAX_FROZEN_SOURCES) return;
750
+ const sourceKeys = /* @__PURE__ */ new Set();
751
+ const sourceRefs = /* @__PURE__ */ new Set();
752
+ const sources = [];
753
+ for (const rawSource of rawSources) {
754
+ if (!isPlainObject(rawSource)) return void 0;
755
+ const rawSourceKeys = Object.keys(rawSource).sort((a, b) => a.localeCompare(b));
756
+ if (rawSourceKeys.length !== 3) return void 0;
757
+ if (rawSourceKeys[0] !== "canonicalKey") return void 0;
758
+ if (rawSourceKeys[1] !== "componentId") return void 0;
759
+ if (rawSourceKeys[2] !== "sourceRef") return void 0;
760
+ const parsed = parseFrozenSource(rawSource, sourceKeys, sourceRefs);
761
+ if (!parsed) return void 0;
762
+ sources.push(parsed);
763
+ }
764
+ return sources;
765
+ }
766
+ function parseMaxSourceBytes(limits) {
767
+ const limitKeys = Object.keys(limits);
768
+ if (limitKeys.length !== 1) return void 0;
769
+ if (limitKeys[0] !== "maxSourceBytes") return void 0;
770
+ const maxSourceBytes = limits.maxSourceBytes;
771
+ if (typeof maxSourceBytes !== "number") return void 0;
772
+ if (!Number.isSafeInteger(maxSourceBytes)) return void 0;
773
+ if (maxSourceBytes < 1) return void 0;
774
+ if (maxSourceBytes > MAX_FROZEN_SOURCE_BYTES) return void 0;
775
+ return maxSourceBytes;
776
+ }
777
+ function parseAiReviewIdentity(constraint) {
778
+ const reviewId = requiredUuid(constraint.reviewId);
779
+ const runId = requiredUuid(constraint.runId);
780
+ const systemSid = requiredIdentifier(constraint.systemSid);
781
+ if (!reviewId) return void 0;
782
+ if (!runId) return void 0;
783
+ if (!systemSid) return void 0;
784
+ if (systemSid.length > 16) return void 0;
785
+ return Object.freeze({
786
+ reviewId,
787
+ runId,
788
+ systemSid
789
+ });
790
+ }
791
+ function parseAiReviewFrozenSourcePolicy(claims) {
792
+ if (claims.agentId !== "ai-review") return void 0;
793
+ const constraint = claims.constraint;
794
+ if (!isSortedKeysEqual(Object.keys(constraint).sort((a, b) => a.localeCompare(b)), expectedAiReviewConstraintKeys)) return;
795
+ if (constraint.kind !== "ai-review-frozen-v1") return void 0;
796
+ const identity = parseAiReviewIdentity(constraint);
797
+ if (!identity) return void 0;
798
+ const sources = parseAiReviewSources(constraint.frozenSources);
799
+ if (!sources) return void 0;
800
+ const maxSourceBytes = parseMaxSourceBytes(claims.limits);
801
+ if (maxSourceBytes === void 0) return void 0;
802
+ return Object.freeze({
803
+ reviewId: identity.reviewId,
804
+ runId: identity.runId,
805
+ systemSid: identity.systemSid,
806
+ sources: Object.freeze(sources),
807
+ maxSourceBytes
808
+ });
809
+ }
810
+ function requiredString(value, options) {
811
+ if (typeof value !== "string") return void 0;
812
+ if (value.length === 0 || value.length > options.maxLength) return void 0;
813
+ if (options.trim && value.trim().length === 0) return void 0;
814
+ if (!options.allowControlChars && /[\s\u0000-\u0008\u000e-\u001f\u007f]/u.test(value)) return;
815
+ return value;
816
+ }
817
+ function requiredIdentifier(value) {
818
+ return requiredString(value, {
819
+ maxLength: MAX_IDENTIFIER_LENGTH,
820
+ trim: true,
821
+ allowControlChars: true
822
+ });
823
+ }
824
+ function requiredSystemSid(value) {
825
+ const systemSid = requiredIdentifier(value);
826
+ return systemSid && systemSid.length <= 16 && /^[A-Za-z0-9_-]+$/u.test(systemSid) ? systemSid : void 0;
827
+ }
828
+ function requiredComponentIdentifier(value) {
829
+ return requiredString(value, { maxLength: MAX_COMPONENT_IDENTIFIER_LENGTH });
830
+ }
831
+ function requiredConfigurationIdentifier(value, name) {
832
+ const identifier = requiredIdentifier(value);
833
+ if (!identifier) throw new Error(`MCP invocation verifier requires a valid ${name}`);
834
+ return identifier;
835
+ }
836
+ function extractBearerCredential(authorizationHeader) {
837
+ if (Array.isArray(authorizationHeader)) return void 0;
838
+ if (typeof authorizationHeader !== "string") return void 0;
839
+ const header = authorizationHeader.trim();
840
+ if (header.length < 8 || header.slice(0, 7).toLowerCase() !== "bearer ") return;
841
+ const credential = header.slice(7).trim();
842
+ return credential.length > 0 ? credential : void 0;
843
+ }
844
+ function isTrustedOperationClass(value) {
845
+ return typeof value === "string" && trustedOperationClasses.has(value);
846
+ }
847
+ function cloneTrustedClasses(value) {
848
+ if (!Array.isArray(value) || value.length === 0) return void 0;
849
+ const classes = [];
850
+ for (const item of value) {
851
+ if (!isTrustedOperationClass(item) || classes.includes(item)) return;
852
+ classes.push(item);
853
+ }
854
+ return Object.freeze(classes);
855
+ }
856
+ function cloneDestinationKeys(value) {
857
+ if (!Array.isArray(value) || value.length === 0) return void 0;
858
+ const destinationKeys = [];
859
+ for (const item of value) {
860
+ if (typeof item !== "string" || !destinationKeyPattern.test(item) || destinationKeys.includes(item)) return;
861
+ destinationKeys.push(item);
862
+ }
863
+ return Object.freeze(destinationKeys);
864
+ }
865
+ function isPlainObject(value) {
866
+ if (value === null) return false;
867
+ if (typeof value !== "object") return false;
868
+ if (Array.isArray(value)) return false;
869
+ const prototype = Object.getPrototypeOf(value);
870
+ return prototype === Object.prototype || prototype === null;
871
+ }
872
+ function cloneJsonScalar(value) {
873
+ if (value === null) return null;
874
+ if (typeof value === "string") return value;
875
+ if (typeof value === "boolean") return value;
876
+ if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
877
+ }
878
+ function cloneJsonArray(value, depth) {
879
+ const cloned = [];
880
+ for (const item of value) {
881
+ const clonedItem = cloneJsonValue(item, depth + 1);
882
+ if (clonedItem === void 0) return void 0;
883
+ cloned.push(clonedItem);
884
+ }
885
+ return Object.freeze(cloned);
886
+ }
887
+ function cloneJsonObject(value, depth) {
888
+ const cloned = Object.create(null);
889
+ for (const [key, item] of Object.entries(value)) {
890
+ const clonedItem = cloneJsonValue(item, depth + 1);
891
+ if (clonedItem === void 0) return void 0;
892
+ cloned[key] = clonedItem;
893
+ }
894
+ return Object.freeze(cloned);
895
+ }
896
+ function cloneJsonValue(value, depth = 0) {
897
+ if (depth > MAX_JSON_DEPTH) return void 0;
898
+ const scalar = cloneJsonScalar(value);
899
+ if (scalar !== void 0) return scalar;
900
+ if (Array.isArray(value)) return cloneJsonArray(value, depth);
901
+ if (isPlainObject(value)) return cloneJsonObject(value, depth);
902
+ }
903
+ function cloneJsonRecord(value) {
904
+ const cloned = cloneJsonValue(value);
905
+ return cloned !== null && !Array.isArray(cloned) && typeof cloned === "object" ? cloned : void 0;
906
+ }
907
+ function isUnixTimestamp(value) {
908
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
909
+ }
910
+ function isValidTokenTimestamps(record) {
911
+ if (!isUnixTimestamp(record.iat)) return false;
912
+ if (!isUnixTimestamp(record.nbf)) return false;
913
+ if (!isUnixTimestamp(record.exp)) return false;
914
+ if (record.nbf < record.iat) return false;
915
+ if (record.exp < record.nbf) return false;
916
+ if (record.exp - record.iat > MAX_TOKEN_LIFETIME_SECONDS) return false;
917
+ return true;
918
+ }
919
+ function isValidTokenHeader(record, expectedKeyId, expectedIssuer, expectedAudience) {
920
+ if (record.v !== INVOCATION_VERSION) return false;
921
+ if (record.kid !== expectedKeyId) return false;
922
+ if (record.iss !== expectedIssuer) return false;
923
+ if (record.aud !== expectedAudience) return false;
924
+ return isValidTokenTimestamps(record);
925
+ }
926
+ function isValidTokenAgent(agentId) {
927
+ return typeof agentId === "string" && trustedAgentIds.has(agentId);
928
+ }
929
+ function parseInvocationActors(record) {
930
+ const tokenId = requiredIdentifier(record.jti);
931
+ const principal = requiredIdentifier(record.principal);
932
+ const correlationId = requiredIdentifier(record.correlationId);
933
+ const agentId = record.agentId;
934
+ if (!tokenId || !principal || !correlationId || !isValidTokenAgent(agentId)) return;
935
+ return Object.freeze({
936
+ tokenId,
937
+ principal,
938
+ agentId,
939
+ correlationId
940
+ });
941
+ }
942
+ function buildInvocationClaims(record) {
943
+ const actors = parseInvocationActors(record);
944
+ if (!actors) return void 0;
945
+ const classes = cloneTrustedClasses(record.classes);
946
+ const destinationKeys = cloneDestinationKeys(record.destinationKeys);
947
+ const constraint = cloneJsonRecord(record.constraint);
948
+ const limits = cloneJsonRecord(record.limits);
949
+ if (!classes) return void 0;
950
+ if (!destinationKeys) return void 0;
951
+ if (!constraint) return void 0;
952
+ if (!limits) return void 0;
953
+ return Object.freeze({
954
+ tokenId: actors.tokenId,
955
+ principal: actors.principal,
956
+ agentId: actors.agentId,
957
+ classes,
958
+ destinationKeys,
959
+ correlationId: actors.correlationId,
960
+ constraint,
961
+ limits
962
+ });
963
+ }
964
+ function claimsFromPayload(payload, expectedKeyId, expectedIssuer, expectedAudience) {
965
+ const record = payload;
966
+ if (!isValidTokenHeader(record, expectedKeyId, expectedIssuer, expectedAudience)) return;
967
+ return buildInvocationClaims(record);
968
+ }
969
+ function currentDate(now) {
970
+ const value = now?.() ?? /* @__PURE__ */ new Date();
971
+ return value instanceof Date ? value : new Date(value);
972
+ }
973
+ /**
974
+ * Build a fail-closed verifier for the one ADT-Server invocation key.
975
+ * Configuration failures throw before serving traffic; credential failures
976
+ * always resolve to `undefined` without logging token-derived information.
977
+ */
978
+ function createMcpInvocationVerifier(options) {
979
+ if (!options?.publicKey) throw new Error("MCP invocation verifier requires an ES256 public key");
980
+ const publicKey = options.publicKey;
981
+ const keyId = requiredConfigurationIdentifier(options.keyId, "key id");
982
+ const issuer = requiredConfigurationIdentifier(options.issuer, "issuer");
983
+ const audience = requiredConfigurationIdentifier(options.audience, "audience");
984
+ const now = options.now;
985
+ return { async verify(authorizationHeader) {
986
+ const credential = extractBearerCredential(authorizationHeader);
987
+ if (!credential) return void 0;
988
+ try {
989
+ const verified = await jwtVerify(credential, publicKey, {
990
+ algorithms: ["ES256"],
991
+ issuer,
992
+ audience,
993
+ currentDate: currentDate(now)
994
+ });
995
+ const protectedHeader = verified.protectedHeader;
996
+ if (protectedHeader.alg !== "ES256" || protectedHeader.kid !== keyId || protectedHeader.typ !== "JWT") return;
997
+ return claimsFromPayload(verified.payload, keyId, issuer, audience);
998
+ } catch {
999
+ return;
1000
+ }
1001
+ } };
1002
+ }
1003
+
1004
+ //#endregion
1005
+ //#region src/lib/http/cors.ts
1006
+ const ALLOW_METHODS = "POST, GET, DELETE, OPTIONS";
1007
+ const ALLOW_HEADERS = "content-type, accept, mcp-session-id, authorization";
1008
+ const EXPOSE_HEADERS = "mcp-session-id";
1009
+ const MAX_AGE = "600";
1010
+ function getOrigin(req) {
1011
+ const raw = req.headers["origin"];
1012
+ const value = Array.isArray(raw) ? raw[0] : raw;
1013
+ return value?.trim() && value.trim().length > 0 ? value.trim() : void 0;
1014
+ }
1015
+ function isAllowed(origin, allowed) {
1016
+ if (allowed.length === 1 && allowed[0] === "*") return true;
1017
+ return allowed.includes(origin);
1018
+ }
1019
+ function createCorsHandler(options = {}) {
1020
+ const allowed = (options.allowedOrigins ?? []).filter((s) => s.length > 0);
1021
+ const enabled = allowed.length > 0;
1022
+ return { handle(req, res) {
1023
+ if (!enabled) return false;
1024
+ const origin = getOrigin(req);
1025
+ const isPreflight = req.method === "OPTIONS";
1026
+ if (!origin) return false;
1027
+ if (!isAllowed(origin, allowed)) {
1028
+ res.writeHead(403, { "Content-Type": "application/json" });
1029
+ res.end(JSON.stringify({ error: "origin not allowed" }));
1030
+ return true;
1031
+ }
1032
+ res.setHeader("Access-Control-Allow-Origin", origin);
1033
+ res.setHeader("Vary", "Origin");
1034
+ res.setHeader("Access-Control-Expose-Headers", EXPOSE_HEADERS);
1035
+ if (isPreflight) {
1036
+ res.setHeader("Access-Control-Allow-Methods", ALLOW_METHODS);
1037
+ res.setHeader("Access-Control-Allow-Headers", ALLOW_HEADERS);
1038
+ res.setHeader("Access-Control-Max-Age", MAX_AGE);
1039
+ res.writeHead(204);
1040
+ res.end();
1041
+ return true;
1042
+ }
1043
+ return false;
1044
+ } };
1045
+ }
1046
+
1047
+ //#endregion
1048
+ //#region src/lib/http/server.ts
1049
+ /**
1050
+ * HTTP transport for the adt-mcp server.
1051
+ *
1052
+ * Implements the Streamable HTTP pattern recommended by the MCP SDK:
1053
+ *
1054
+ * - POST /mcp with `initialize` and no `Mcp-Session-Id` header
1055
+ * → spin up a new McpServer + StreamableHTTPServerTransport pair,
1056
+ * register them under the generated session id.
1057
+ * - Subsequent POST /mcp / GET /mcp / DELETE /mcp with `Mcp-Session-Id`
1058
+ * → route to the stored transport.
1059
+ *
1060
+ * A small middleware pipeline (`host validation → auth → route`) is kept
1061
+ * simple and composable so that future waves can drop in real auth.
1062
+ */
1063
+ /**
1064
+ * Captures trusted access at initialization so a provider cannot change a
1065
+ * session's authorization by mutating the object it returned later.
1066
+ */
1067
+ function snapshotRequestAccess(access) {
1068
+ if (!access) return void 0;
1069
+ const classes = access.classes;
1070
+ const destinationKeys = access.destinationKeys;
1071
+ if (!Array.isArray(classes) || !Array.isArray(destinationKeys)) return;
1072
+ if (!classes.every(isMcpOperationClass) || !destinationKeys.every(isMcpDestinationKey)) return;
1073
+ const frozenSource = snapshotFrozenSourceAccess(access.frozenSource);
1074
+ if (access.frozenSource && !frozenSource) return void 0;
1075
+ const scoped = snapshotScopedAccess(access.scoped);
1076
+ if (access.scoped && !scoped) return void 0;
1077
+ const delegated = snapshotDelegatedAccess(access.delegated);
1078
+ if (access.delegated && !delegated) return void 0;
1079
+ if (scoped && (classes.length !== 2 || classes[0] !== "server" || classes[1] !== scoped.operationClass)) return;
1080
+ return Object.freeze({
1081
+ classes: Object.freeze([...classes]),
1082
+ destinationKeys: Object.freeze([...destinationKeys]),
1083
+ ...frozenSource ? { frozenSource } : {},
1084
+ ...scoped ? { scoped } : {},
1085
+ ...delegated ? { delegated } : {}
1086
+ });
1087
+ }
1088
+ const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;
1089
+ const OBJECT_KEY_REGEX = /^[A-Z0-9_]{2,30}:[A-Z0-9_/$-]{1,128}$/u;
1090
+ const READ_SCOPED_TOOLS = /* @__PURE__ */ new Set(["get_object", "get_object_structure"]);
1091
+ const SYSTEM_SID_REGEX = /^[A-Za-z0-9_-]{1,16}$/u;
1092
+ const AUTHORIZATION_TOKEN_REGEX = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/u;
1093
+ function normalizeAndValidateStrings(values) {
1094
+ if (!Array.isArray(values)) return void 0;
1095
+ const result = [];
1096
+ for (const value of values) {
1097
+ if (typeof value !== "string" || !value) return void 0;
1098
+ result.push(value);
1099
+ }
1100
+ return result;
1101
+ }
1102
+ function isSortedUniqueStrings(values) {
1103
+ const sorted = [...values].sort((left, right) => left.localeCompare(right));
1104
+ return new Set(values).size === values.length && values.every((value, index) => value === sorted[index]);
1105
+ }
1106
+ function validateCommonScopedFields(access) {
1107
+ if (typeof access.tokenId !== "string" || !access.tokenId) return void 0;
1108
+ if (typeof access.principal !== "string" || !access.principal) return void 0;
1109
+ if (typeof access.correlationId !== "string" || !access.correlationId) return void 0;
1110
+ if (typeof access.scopeId !== "string" || !UUID_REGEX.test(access.scopeId)) return;
1111
+ if (typeof access.executionId !== "string" || !UUID_REGEX.test(access.executionId)) return;
1112
+ if (typeof access.systemSid !== "string" || !SYSTEM_SID_REGEX.test(access.systemSid)) return;
1113
+ if (!Number.isSafeInteger(access.maxToolCalls) || access.maxToolCalls < 1 || access.maxToolCalls > 12) return;
1114
+ const resourceKeys = normalizeAndValidateStrings(access.resourceKeys);
1115
+ const toolNames = normalizeAndValidateStrings(access.toolNames);
1116
+ if (!resourceKeys || resourceKeys.length > 100 || resourceKeys.some((key) => !OBJECT_KEY_REGEX.test(key)) || !isSortedUniqueStrings(resourceKeys) || !toolNames || toolNames.length === 0 || !isSortedUniqueStrings(toolNames)) return;
1117
+ return {
1118
+ resourceKeys,
1119
+ toolNames
1120
+ };
1121
+ }
1122
+ function buildScopedAccess(access, resourceKeys, toolNames, overrides = {}) {
1123
+ return Object.freeze({
1124
+ ...access,
1125
+ resourceKeys: Object.freeze(resourceKeys),
1126
+ toolNames: Object.freeze(toolNames),
1127
+ ...overrides
1128
+ });
1129
+ }
1130
+ function snapshotReadScope(access, resourceKeys, toolNames) {
1131
+ if (resourceKeys.length === 0 || toolNames.some((name) => !READ_SCOPED_TOOLS.has(name)) || access.safeExecutePolicy !== void 0 || access.authorizationId !== void 0 || access.authorizationToken !== void 0) return;
1132
+ return buildScopedAccess(access, resourceKeys, toolNames);
1133
+ }
1134
+ function snapshotSafeExecuteScope(access, resourceKeys, toolNames) {
1135
+ const safeExecutePolicy = parseSafeExecutePolicy(access.safeExecutePolicy);
1136
+ if (!safeExecutePolicy || resourceKeys.length === 0 || toolNames.length !== 1 || toolNames[0] !== safeExecutePolicy.operationId || typeof access.authorizationId !== "string" || !UUID_REGEX.test(access.authorizationId) || typeof access.authorizationToken !== "string" || access.authorizationToken.length > 16384 || !AUTHORIZATION_TOKEN_REGEX.test(access.authorizationToken)) return;
1137
+ return buildScopedAccess(access, resourceKeys, toolNames, { safeExecutePolicy });
1138
+ }
1139
+ function snapshotScopedAccess(access) {
1140
+ if (!access) return void 0;
1141
+ const validated = validateCommonScopedFields(access);
1142
+ if (!validated) return void 0;
1143
+ const { resourceKeys, toolNames } = validated;
1144
+ if (access.operationClass === "read") return snapshotReadScope(access, resourceKeys, toolNames);
1145
+ if (access.operationClass === "safe_execute") return snapshotSafeExecuteScope(access, resourceKeys, toolNames);
1146
+ }
1147
+ function snapshotDelegatedAccess(access) {
1148
+ if (!access) return void 0;
1149
+ if (typeof access.threadId !== "string" || !UUID_REGEX.test(access.threadId) || typeof access.executionId !== "string" || !UUID_REGEX.test(access.executionId) || typeof access.systemSid !== "string" || access.systemSid.length === 0 || access.systemSid.length > 16) return;
1150
+ return Object.freeze({
1151
+ threadId: access.threadId,
1152
+ executionId: access.executionId,
1153
+ systemSid: access.systemSid
1154
+ });
1155
+ }
1156
+ function snapshotFrozenSourceAccess(access) {
1157
+ if (!access) return void 0;
1158
+ if (typeof access.systemSid !== "string" || access.systemSid.length === 0 || access.systemSid.length > 16 || !Number.isSafeInteger(access.maxSourceBytes) || access.maxSourceBytes < 1 || access.maxSourceBytes > 2097152 || !Array.isArray(access.sources) || access.sources.length === 0 || access.sources.length > 500) return;
1159
+ const sourceKeys = /* @__PURE__ */ new Set();
1160
+ const sourceRefs = /* @__PURE__ */ new Set();
1161
+ const sources = [];
1162
+ for (const source of access.sources) {
1163
+ const parsed = parseFrozenSource(source, sourceKeys, sourceRefs);
1164
+ if (!parsed) return void 0;
1165
+ sources.push(parsed);
1166
+ }
1167
+ return Object.freeze({
1168
+ systemSid: access.systemSid,
1169
+ sources: Object.freeze(sources),
1170
+ maxSourceBytes: access.maxSourceBytes
1171
+ });
1172
+ }
1173
+ /** A deterministic, non-secret value used only for session affinity checks. */
1174
+ function sessionIdentityBinding(identity, invocationTokenId) {
1175
+ if (!identity.principal || typeof identity.principal !== "string") throw new Error("Trusted request identity is missing a principal");
1176
+ if (identity.agentId !== void 0 && typeof identity.agentId !== "string") throw new Error("Trusted request identity has an invalid agent id");
1177
+ return JSON.stringify([
1178
+ identity.principal,
1179
+ identity.agentId ?? null,
1180
+ invocationTokenId ?? null
1181
+ ]);
1182
+ }
1183
+ function invocationRequestIdentity(invocation) {
1184
+ if (!invocation) throw new Error("Trusted MCP invocation identity is missing");
1185
+ return {
1186
+ principal: invocation.principal,
1187
+ agentId: invocation.agentId
1188
+ };
1189
+ }
1190
+ function invocationRequestAccess(invocation) {
1191
+ if (!invocation || !isMcpInvocationDispatchPolicySupported(invocation)) return;
1192
+ const frozenSource = parseAiReviewFrozenSourcePolicy(invocation);
1193
+ const scopedPolicy = parseScopedAdtInvocationPolicy(invocation);
1194
+ const delegated = parseDelegatedAssistantReadPolicy(invocation);
1195
+ return snapshotRequestAccess({
1196
+ classes: invocation.classes,
1197
+ destinationKeys: invocation.destinationKeys,
1198
+ ...frozenSource ? { frozenSource } : {},
1199
+ ...scopedPolicy ? { scoped: {
1200
+ tokenId: invocation.tokenId,
1201
+ principal: invocation.principal,
1202
+ correlationId: invocation.correlationId,
1203
+ ...scopedPolicy
1204
+ } } : {},
1205
+ ...delegated ? { delegated } : {}
1206
+ });
1207
+ }
1208
+ function defaultLog(level, msg) {
1209
+ const line = `[adt-mcp-http] ${level}: ${msg}\n`;
1210
+ process.stderr.write(line);
1211
+ }
1212
+ function normaliseHostAllowlist(bindHost, extra) {
1213
+ const set = /* @__PURE__ */ new Set([
1214
+ "localhost",
1215
+ "127.0.0.1",
1216
+ "[::1]",
1217
+ "::1"
1218
+ ]);
1219
+ if (bindHost) set.add(bindHost.toLowerCase());
1220
+ for (const h of extra ?? []) set.add(h.toLowerCase());
1221
+ return set;
1222
+ }
1223
+ /**
1224
+ * Host-header validation middleware — protects against DNS-rebinding
1225
+ * attacks when the server binds to a loopback interface. Returns `true`
1226
+ * when the request has been rejected (caller should stop processing).
1227
+ */
1228
+ function makeHostValidator(allowed) {
1229
+ return (req, res) => {
1230
+ const hostHeader = req.headers.host ?? "";
1231
+ const host = hostHeader.replace(/:\d+$/u, "").toLowerCase();
1232
+ if (!host || !allowed.has(host)) {
1233
+ res.writeHead(403, { "Content-Type": "application/json" });
1234
+ res.end(JSON.stringify({
1235
+ jsonrpc: "2.0",
1236
+ error: {
1237
+ code: -32e3,
1238
+ message: `Host header '${hostHeader}' not allowed`
1239
+ },
1240
+ id: null
1241
+ }));
1242
+ return true;
1243
+ }
1244
+ return false;
1245
+ };
1246
+ }
1247
+ async function readJsonBody(req, limitBytes = 4194304) {
1248
+ return await new Promise((resolve, reject) => {
1249
+ let total = 0;
1250
+ const chunks = [];
1251
+ req.on("data", (chunk) => {
1252
+ total += chunk.length;
1253
+ if (total > limitBytes) {
1254
+ reject(/* @__PURE__ */ new Error("Request body too large"));
1255
+ req.destroy();
1256
+ return;
1257
+ }
1258
+ chunks.push(chunk);
1259
+ });
1260
+ req.on("end", () => {
1261
+ if (chunks.length === 0) {
1262
+ resolve(void 0);
1263
+ return;
1264
+ }
1265
+ const raw = Buffer.concat(chunks).toString("utf8");
1266
+ try {
1267
+ resolve(raw.length === 0 ? void 0 : JSON.parse(raw));
1268
+ } catch (err) {
1269
+ reject(err);
1270
+ }
1271
+ });
1272
+ req.on("error", reject);
1273
+ });
1274
+ }
1275
+ function isInitializeRequest(body) {
1276
+ if (!body) return false;
1277
+ return (Array.isArray(body) ? body : [body]).some((m) => m && typeof m === "object" && m.method === "initialize");
1278
+ }
1279
+ function writeJsonError(res, status, message) {
1280
+ if (res.headersSent) {
1281
+ try {
1282
+ res.end();
1283
+ } catch {}
1284
+ return;
1285
+ }
1286
+ res.writeHead(status, { "Content-Type": "application/json" });
1287
+ res.end(JSON.stringify({
1288
+ jsonrpc: "2.0",
1289
+ error: {
1290
+ code: -32e3,
1291
+ message
1292
+ },
1293
+ id: null
1294
+ }));
1295
+ }
1296
+ /**
1297
+ * Creates a reusable MCP HTTP handler without binding a Node listener.
1298
+ */
1299
+ function createHttpMcpHandler(options = {}) {
1300
+ const host = options.host ?? process.env.MCP_HOST ?? "127.0.0.1";
1301
+ const log = options.log ?? defaultLog;
1302
+ const registry = options.registry ?? createSessionRegistry({ ttlMs: options.ttlMs ?? 18e5 });
1303
+ const multiSystem = options.multiSystem ?? loadMultiSystemConfig();
1304
+ const destinationServer = options.destinationServer;
1305
+ const transports = /* @__PURE__ */ new Map();
1306
+ const servers = /* @__PURE__ */ new Map();
1307
+ const sessionIdentityBindings = /* @__PURE__ */ new Map();
1308
+ async function releaseSessionResources(sessionId) {
1309
+ const server = servers.get(sessionId);
1310
+ transports.delete(sessionId);
1311
+ sessionIdentityBindings.delete(sessionId);
1312
+ servers.delete(sessionId);
1313
+ await registry.delete(sessionId);
1314
+ await destinationServer?.destinationRegistry.releaseAll(sessionId);
1315
+ try {
1316
+ await server?.close();
1317
+ } catch {}
1318
+ }
1319
+ const hostValidator = makeHostValidator(normaliseHostAllowlist(host, options.allowedHosts));
1320
+ let authMode = options.authMode ?? (options.authToken ? "bearer" : "none");
1321
+ if (options.trustForwardedAuth && authMode === "none") authMode = "proxy";
1322
+ if (authMode === "oauth" && !options.oauth) throw new Error("startHttpServer: authMode=oauth requires `oauth` options (issuer at minimum)");
1323
+ if (authMode === "invocation" && !options.invocationVerifier) throw new Error("createHttpMcpHandler: authMode=invocation requires an invocation verifier");
1324
+ if (authMode === "invocation" && !destinationServer) throw new Error("createHttpMcpHandler: authMode=invocation requires destinationServer scope enforcement");
1325
+ const authMw = createAuthMiddleware({
1326
+ mode: authMode,
1327
+ token: options.authToken,
1328
+ oauth: options.oauth,
1329
+ invocationVerifier: options.invocationVerifier,
1330
+ onUserHint: options.onOAuthUserHint
1331
+ });
1332
+ const cors = createCorsHandler({ allowedOrigins: options.allowedOrigins });
1333
+ const sessionMatchesAuthenticatedIdentity = (sessionId, userHint, invocation, res) => {
1334
+ if (!destinationServer) return true;
1335
+ const expected = sessionIdentityBindings.get(sessionId);
1336
+ if (!expected) {
1337
+ writeJsonError(res, 403, "mcp_session_identity_mismatch");
1338
+ return false;
1339
+ }
1340
+ try {
1341
+ if (sessionIdentityBinding(authMode === "invocation" ? invocationRequestIdentity(invocation) : destinationServer.requestIdentity({
1342
+ userHint,
1343
+ invocation
1344
+ }), invocation?.tokenId) === expected) return true;
1345
+ } catch {}
1346
+ writeJsonError(res, 403, "mcp_session_identity_mismatch");
1347
+ return false;
1348
+ };
1349
+ const handleMcp = async (req, res, userHint, invocation) => {
1350
+ const sessionHeader = req.headers["mcp-session-id"];
1351
+ const sessionId = Array.isArray(sessionHeader) ? sessionHeader[0] : sessionHeader;
1352
+ if (req.method === "POST") {
1353
+ let body;
1354
+ try {
1355
+ body = await readJsonBody(req);
1356
+ } catch (err) {
1357
+ writeJsonError(res, 400, `Invalid JSON body: ${err instanceof Error ? err.message : String(err)}`);
1358
+ return;
1359
+ }
1360
+ if (sessionId && transports.has(sessionId)) {
1361
+ if (!sessionMatchesAuthenticatedIdentity(sessionId, userHint, invocation, res)) return;
1362
+ registry.touch(sessionId);
1363
+ await transports.get(sessionId).handleRequest(req, res, body);
1364
+ return;
1365
+ }
1366
+ if (!sessionId && isInitializeRequest(body)) {
1367
+ let initializedSessionBinding;
1368
+ const transport = new StreamableHTTPServerTransport({
1369
+ sessionIdGenerator: () => randomUUID(),
1370
+ onsessioninitialized: (id) => {
1371
+ transports.set(id, transport);
1372
+ if (initializedSessionBinding) sessionIdentityBindings.set(id, initializedSessionBinding);
1373
+ log("info", `session initialized: ${id}`);
1374
+ },
1375
+ onsessionclosed: async (id) => {
1376
+ log("info", `session closed by client: ${id}`);
1377
+ await releaseSessionResources(id);
1378
+ }
1379
+ });
1380
+ transport.onclose = () => {
1381
+ const id = transport.sessionId;
1382
+ if (!id) return;
1383
+ releaseSessionResources(id);
1384
+ };
1385
+ let sessionIdentity;
1386
+ let sessionAccess;
1387
+ if (destinationServer) {
1388
+ let identityDerivationFailed = false;
1389
+ try {
1390
+ sessionIdentity = authMode === "invocation" ? invocationRequestIdentity(invocation) : destinationServer.requestIdentity({
1391
+ userHint,
1392
+ invocation
1393
+ });
1394
+ initializedSessionBinding = sessionIdentityBinding(sessionIdentity, invocation?.tokenId);
1395
+ } catch {
1396
+ sessionIdentity = { principal: "unknown" };
1397
+ identityDerivationFailed = true;
1398
+ }
1399
+ if (!identityDerivationFailed) try {
1400
+ sessionAccess = authMode === "invocation" ? invocationRequestAccess(invocation) : snapshotRequestAccess(destinationServer.requestAccess({
1401
+ userHint,
1402
+ invocation
1403
+ }));
1404
+ } catch {
1405
+ sessionAccess = void 0;
1406
+ }
1407
+ }
1408
+ const mcp = createMcpServer({
1409
+ registry,
1410
+ resolveSystem: (id) => multiSystem.resolve(id),
1411
+ ...destinationServer ? {
1412
+ destinationRegistry: destinationServer.destinationRegistry,
1413
+ requestIdentity: () => sessionIdentity ?? { principal: "unknown" },
1414
+ requestAccess: () => sessionAccess,
1415
+ ...destinationServer.resolveFrozenSource ? { resolveFrozenSource: destinationServer.resolveFrozenSource } : {},
1416
+ ...destinationServer.consumeExecutionAuthorization ? { consumeExecutionAuthorization: destinationServer.consumeExecutionAuthorization } : {},
1417
+ ...destinationServer.reportExecutionOutcome ? { reportExecutionOutcome: destinationServer.reportExecutionOutcome } : {},
1418
+ ...destinationServer.executeWithDeadline ? { executeWithDeadline: destinationServer.executeWithDeadline } : {}
1419
+ } : {}
1420
+ });
1421
+ await mcp.connect(transport);
1422
+ if (transport.sessionId) {
1423
+ transports.set(transport.sessionId, transport);
1424
+ servers.set(transport.sessionId, mcp);
1425
+ }
1426
+ await transport.handleRequest(req, res, body);
1427
+ if (transport.sessionId && !servers.has(transport.sessionId)) servers.set(transport.sessionId, mcp);
1428
+ return;
1429
+ }
1430
+ writeJsonError(res, 400, sessionId ? `Unknown Mcp-Session-Id: ${sessionId}` : "Missing Mcp-Session-Id header (non-initialize request)");
1431
+ return;
1432
+ }
1433
+ if (req.method === "GET" || req.method === "DELETE") {
1434
+ if (!sessionId || !transports.has(sessionId)) {
1435
+ writeJsonError(res, 400, "Missing or unknown Mcp-Session-Id header");
1436
+ return;
1437
+ }
1438
+ if (!sessionMatchesAuthenticatedIdentity(sessionId, userHint, invocation, res)) return;
1439
+ registry.touch(sessionId);
1440
+ await transports.get(sessionId).handleRequest(req, res);
1441
+ return;
1442
+ }
1443
+ res.writeHead(405, { Allow: "POST, GET, DELETE" });
1444
+ res.end();
1445
+ };
1446
+ const handle = async (req, res) => {
1447
+ try {
1448
+ if (cors.handle(req, res)) return;
1449
+ if (hostValidator(req, res)) return;
1450
+ const pathOnly = (req.url ?? "/").split("?")[0];
1451
+ if (pathOnly === "/healthz" && req.method === "GET") {
1452
+ res.writeHead(200, { "Content-Type": "application/json" });
1453
+ res.end(JSON.stringify({
1454
+ status: "ok",
1455
+ sessions: registry.list().length
1456
+ }));
1457
+ return;
1458
+ }
1459
+ const authResult = await authMw(req, res);
1460
+ if (!authResult.allowed) return;
1461
+ if (pathOnly === "/mcp" || pathOnly === "/mcp/") {
1462
+ await handleMcp(req, res, authResult.userHint, authResult.invocation);
1463
+ return;
1464
+ }
1465
+ res.writeHead(404, { "Content-Type": "application/json" });
1466
+ res.end(JSON.stringify({ error: "Not found" }));
1467
+ } catch (err) {
1468
+ log("error", `unhandled error: ${err instanceof Error ? err.stack ?? err.message : String(err)}`);
1469
+ writeJsonError(res, 500, "Internal server error");
1470
+ }
1471
+ };
1472
+ let closed = false;
1473
+ const close = async () => {
1474
+ if (closed) return;
1475
+ closed = true;
1476
+ log("info", "shutting down");
1477
+ await registry.shutdown();
1478
+ const pairs = Array.from(transports.entries());
1479
+ transports.clear();
1480
+ for (const [sessionId] of pairs) sessionIdentityBindings.delete(sessionId);
1481
+ if (destinationServer) await Promise.allSettled(pairs.map(async ([sessionId]) => await destinationServer.destinationRegistry.releaseAll(sessionId)));
1482
+ await Promise.allSettled(pairs.map(async ([, t]) => {
1483
+ try {
1484
+ await t.close();
1485
+ } catch {}
1486
+ }));
1487
+ const srvs = Array.from(servers.values());
1488
+ servers.clear();
1489
+ await Promise.allSettled(srvs.map(async (s) => {
1490
+ try {
1491
+ await s.close();
1492
+ } catch {}
1493
+ }));
1494
+ };
1495
+ return {
1496
+ registry,
1497
+ handle,
1498
+ close
1499
+ };
1500
+ }
1501
+ /**
1502
+ * Starts the HTTP transport and returns a handle that can be used to close
1503
+ * both the listener and all active MCP sessions gracefully.
1504
+ *
1505
+ * This is a backwards-compatible listener adapter around
1506
+ * `createHttpMcpHandler` for standalone deployments.
1507
+ */
1508
+ async function startHttpServer(options = {}) {
1509
+ const port = options.port ?? (process.env.MCP_PORT ? Number(process.env.MCP_PORT) : 3e3);
1510
+ const host = options.host ?? process.env.MCP_HOST ?? "127.0.0.1";
1511
+ const log = options.log ?? defaultLog;
1512
+ const certPath = options.tlsCert ?? process.env.MCP_TLS_CERT;
1513
+ const keyPath = options.tlsKey ?? process.env.MCP_TLS_KEY;
1514
+ const cert = options.tlsCertContent ?? (certPath ? await readFile(certPath, "utf8") : void 0);
1515
+ const key = options.tlsKeyContent ?? (keyPath ? await readFile(keyPath, "utf8") : void 0);
1516
+ if (!cert || !key) throw new Error("startHttpServer: TLS certificate and key are required. Provide tlsCert/tlsKey, tlsCertContent/tlsKeyContent, or MCP_TLS_CERT/MCP_TLS_KEY.");
1517
+ if (!cert.includes("-----BEGIN CERTIFICATE-----") || !cert.includes("-----END CERTIFICATE-----")) throw new Error("startHttpServer: TLS certificate is not valid PEM — expected a \"-----BEGIN CERTIFICATE-----\" block" + (certPath ? ` in ${certPath}` : " in tlsCertContent") + ".");
1518
+ if (!key.includes("PRIVATE KEY-----")) throw new Error("startHttpServer: TLS private key is not valid PEM — expected a \"-----BEGIN ... PRIVATE KEY-----\" block" + (keyPath ? ` in ${keyPath}` : " in tlsKeyContent") + ".");
1519
+ const handler = createHttpMcpHandler(options);
1520
+ let server;
1521
+ try {
1522
+ server = https.createServer({
1523
+ cert,
1524
+ key
1525
+ }, (req, res) => {
1526
+ handler.handle(req, res);
1527
+ });
1528
+ await new Promise((resolve, reject) => {
1529
+ const onError = (err) => reject(err);
1530
+ server.once("error", onError);
1531
+ server.listen(port, host, () => {
1532
+ server.removeListener("error", onError);
1533
+ resolve();
1534
+ });
1535
+ });
1536
+ } catch (err) {
1537
+ await handler.close().catch(() => void 0);
1538
+ throw err;
1539
+ }
1540
+ const boundPort = server.address()?.port ?? port;
1541
+ log("info", `listening on https://${host}:${boundPort}/mcp`);
1542
+ let closed = false;
1543
+ const close = async () => {
1544
+ if (closed) return;
1545
+ closed = true;
1546
+ await handler.close();
1547
+ server.closeAllConnections();
1548
+ await new Promise((resolve) => server.close(() => resolve()));
1549
+ };
1550
+ return {
1551
+ url: `https://${host}:${boundPort}/mcp`,
1552
+ port: boundPort,
1553
+ host,
1554
+ registry: handler.registry,
1555
+ close
1556
+ };
1557
+ }
1558
+
1559
+ //#endregion
1560
+ export { parseSafeExecutePolicy as a, createSessionRegistry as c, parseDelegatedAssistantReadPolicy as i, startHttpServer as n, parseScopedAdtInvocationPolicy as o, createMcpInvocationVerifier as r, loadMultiSystemConfig as s, createHttpMcpHandler as t };
1561
+ //# sourceMappingURL=server-5bFocUjx.mjs.map