@kontext-dev/js-sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +70 -0
  2. package/dist/adapters/ai/index.cjs +175 -0
  3. package/dist/adapters/ai/index.cjs.map +1 -0
  4. package/dist/adapters/ai/index.d.cts +51 -0
  5. package/dist/adapters/ai/index.d.ts +51 -0
  6. package/dist/adapters/ai/index.js +173 -0
  7. package/dist/adapters/ai/index.js.map +1 -0
  8. package/dist/adapters/cloudflare/index.cjs +598 -0
  9. package/dist/adapters/cloudflare/index.cjs.map +1 -0
  10. package/dist/adapters/cloudflare/index.d.cts +214 -0
  11. package/dist/adapters/cloudflare/index.d.ts +214 -0
  12. package/dist/adapters/cloudflare/index.js +594 -0
  13. package/dist/adapters/cloudflare/index.js.map +1 -0
  14. package/dist/adapters/cloudflare/react.cjs +156 -0
  15. package/dist/adapters/cloudflare/react.cjs.map +1 -0
  16. package/dist/adapters/cloudflare/react.d.cts +68 -0
  17. package/dist/adapters/cloudflare/react.d.ts +68 -0
  18. package/dist/adapters/cloudflare/react.js +152 -0
  19. package/dist/adapters/cloudflare/react.js.map +1 -0
  20. package/dist/adapters/react/index.cjs +146 -0
  21. package/dist/adapters/react/index.cjs.map +1 -0
  22. package/dist/adapters/react/index.d.cts +103 -0
  23. package/dist/adapters/react/index.d.ts +103 -0
  24. package/dist/adapters/react/index.js +142 -0
  25. package/dist/adapters/react/index.js.map +1 -0
  26. package/dist/client/index.cjs +2415 -0
  27. package/dist/client/index.cjs.map +1 -0
  28. package/dist/client/index.d.cts +125 -0
  29. package/dist/client/index.d.ts +125 -0
  30. package/dist/client/index.js +2412 -0
  31. package/dist/client/index.js.map +1 -0
  32. package/dist/errors.cjs +213 -0
  33. package/dist/errors.cjs.map +1 -0
  34. package/dist/errors.d.cts +161 -0
  35. package/dist/errors.d.ts +161 -0
  36. package/dist/errors.js +201 -0
  37. package/dist/errors.js.map +1 -0
  38. package/dist/index-D5hS5PGn.d.ts +54 -0
  39. package/dist/index-DcL4a5Vq.d.cts +54 -0
  40. package/dist/index.cjs +4046 -0
  41. package/dist/index.cjs.map +1 -0
  42. package/dist/index.d.cts +15 -0
  43. package/dist/index.d.ts +15 -0
  44. package/dist/index.js +4029 -0
  45. package/dist/index.js.map +1 -0
  46. package/dist/kontext-CgIBANFo.d.cts +308 -0
  47. package/dist/kontext-CgIBANFo.d.ts +308 -0
  48. package/dist/management/index.cjs +867 -0
  49. package/dist/management/index.cjs.map +1 -0
  50. package/dist/management/index.d.cts +467 -0
  51. package/dist/management/index.d.ts +467 -0
  52. package/dist/management/index.js +855 -0
  53. package/dist/management/index.js.map +1 -0
  54. package/dist/mcp/index.cjs +799 -0
  55. package/dist/mcp/index.cjs.map +1 -0
  56. package/dist/mcp/index.d.cts +231 -0
  57. package/dist/mcp/index.d.ts +231 -0
  58. package/dist/mcp/index.js +797 -0
  59. package/dist/mcp/index.js.map +1 -0
  60. package/dist/oauth/index.cjs +418 -0
  61. package/dist/oauth/index.cjs.map +1 -0
  62. package/dist/oauth/index.d.cts +235 -0
  63. package/dist/oauth/index.d.ts +235 -0
  64. package/dist/oauth/index.js +414 -0
  65. package/dist/oauth/index.js.map +1 -0
  66. package/dist/server/index.cjs +1634 -0
  67. package/dist/server/index.cjs.map +1 -0
  68. package/dist/server/index.d.cts +10 -0
  69. package/dist/server/index.d.ts +10 -0
  70. package/dist/server/index.js +1629 -0
  71. package/dist/server/index.js.map +1 -0
  72. package/dist/types-CzhnlJHW.d.cts +397 -0
  73. package/dist/types-CzhnlJHW.d.ts +397 -0
  74. package/dist/types-RIzHnRpk.d.cts +23 -0
  75. package/dist/types-RIzHnRpk.d.ts +23 -0
  76. package/dist/verifier-CoJmYiw3.d.cts +109 -0
  77. package/dist/verifier-CoJmYiw3.d.ts +109 -0
  78. package/dist/verify/index.cjs +319 -0
  79. package/dist/verify/index.cjs.map +1 -0
  80. package/dist/verify/index.d.cts +63 -0
  81. package/dist/verify/index.d.ts +63 -0
  82. package/dist/verify/index.js +315 -0
  83. package/dist/verify/index.js.map +1 -0
  84. package/package.json +221 -0
@@ -0,0 +1,1629 @@
1
+ import { createHash } from 'crypto';
2
+ import { createRequire } from 'module';
3
+ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
4
+ import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';
5
+ import { mcpAuthMetadataRouter, getOAuthProtectedResourceMetadataUrl } from '@modelcontextprotocol/sdk/server/auth/router.js';
6
+ import { requireBearerAuth } from '@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js';
7
+ import { InvalidTokenError } from '@modelcontextprotocol/sdk/server/auth/errors.js';
8
+ import { jwtVerify, errors, decodeProtectedHeader, createRemoteJWKSet } from 'jose';
9
+
10
+ // src/server/kontext.ts
11
+
12
+ // src/management/types.ts
13
+ var TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange";
14
+ var TOKEN_TYPE_ACCESS_TOKEN = "urn:ietf:params:oauth:token-type:access_token";
15
+
16
+ // src/errors.ts
17
+ var KontextError = class extends Error {
18
+ /** Brand field for type narrowing without instanceof */
19
+ kontextError = true;
20
+ /** Machine-readable error code, always prefixed with `kontext_` */
21
+ code;
22
+ /** HTTP status code when applicable */
23
+ statusCode;
24
+ /** Auto-generated link to error documentation */
25
+ docsUrl;
26
+ /** Server request ID for debugging / support escalation */
27
+ requestId;
28
+ /** Contextual metadata bag (integration IDs, param names, etc.) */
29
+ meta;
30
+ constructor(message, code, options) {
31
+ super(message, { cause: options?.cause });
32
+ this.name = "KontextError";
33
+ this.code = code;
34
+ this.statusCode = options?.statusCode;
35
+ this.requestId = options?.requestId;
36
+ this.meta = options?.meta ?? {};
37
+ this.docsUrl = `https://docs.kontext.dev/errors/${code}`;
38
+ Object.setPrototypeOf(this, new.target.prototype);
39
+ }
40
+ toJSON() {
41
+ return {
42
+ name: this.name,
43
+ code: this.code,
44
+ message: this.message,
45
+ statusCode: this.statusCode,
46
+ docsUrl: this.docsUrl,
47
+ requestId: this.requestId,
48
+ meta: Object.keys(this.meta).length > 0 ? this.meta : void 0
49
+ };
50
+ }
51
+ toString() {
52
+ const parts = [`[${this.code}] ${this.message}`];
53
+ if (this.docsUrl) parts.push(`Docs: ${this.docsUrl}`);
54
+ if (this.requestId) parts.push(`Request ID: ${this.requestId}`);
55
+ return parts.join("\n");
56
+ }
57
+ };
58
+ var OAuthError = class extends KontextError {
59
+ errorCode;
60
+ errorDescription;
61
+ constructor(message, code, options) {
62
+ super(message, code, {
63
+ statusCode: options?.statusCode ?? 400,
64
+ ...options
65
+ });
66
+ this.name = "OAuthError";
67
+ this.errorCode = options?.errorCode;
68
+ this.errorDescription = options?.errorDescription;
69
+ }
70
+ };
71
+ var IntegrationConnectionRequiredError = class extends KontextError {
72
+ integrationId;
73
+ integrationName;
74
+ connectUrl;
75
+ constructor(integrationId, options) {
76
+ super(
77
+ options?.message ?? `Connection to integration "${integrationId}" is required. Visit the connect URL to authorize.`,
78
+ "kontext_integration_connection_required",
79
+ { statusCode: 403, ...options }
80
+ );
81
+ this.name = "IntegrationConnectionRequiredError";
82
+ this.integrationId = integrationId;
83
+ this.integrationName = options?.integrationName;
84
+ this.connectUrl = options?.connectUrl;
85
+ }
86
+ };
87
+
88
+ // src/oauth/token-exchange.ts
89
+ async function exchangeToken(config, subjectToken, resource, scope, subjectTokenType = TOKEN_TYPE_ACCESS_TOKEN) {
90
+ const body = new URLSearchParams();
91
+ body.set("grant_type", TOKEN_EXCHANGE_GRANT_TYPE);
92
+ body.set("subject_token", subjectToken);
93
+ body.set("subject_token_type", subjectTokenType);
94
+ body.set("resource", resource);
95
+ const headers = {
96
+ "Content-Type": "application/x-www-form-urlencoded"
97
+ };
98
+ if (config.clientSecret) {
99
+ const credentials = Buffer.from(
100
+ `${config.clientId}:${config.clientSecret}`
101
+ ).toString("base64");
102
+ headers["Authorization"] = `Basic ${credentials}`;
103
+ } else {
104
+ body.set("client_id", config.clientId);
105
+ }
106
+ const response = await fetch(config.tokenUrl, {
107
+ method: "POST",
108
+ headers,
109
+ body: body.toString()
110
+ });
111
+ if (!response.ok) {
112
+ let errorMessage = `Token exchange failed: ${response.status} ${response.statusText}`;
113
+ let errorCode;
114
+ let integrationName;
115
+ let integrationId;
116
+ try {
117
+ const errorBody = await response.json();
118
+ errorCode = errorBody.error;
119
+ if (errorBody.error_description) {
120
+ errorMessage = errorBody.error_description;
121
+ } else if (errorBody.error) {
122
+ errorMessage = `Token exchange failed: ${errorBody.error}`;
123
+ }
124
+ if (errorBody.integration_name || errorBody.integration_id) {
125
+ integrationName = errorBody.integration_name;
126
+ integrationId = errorBody.integration_id;
127
+ }
128
+ } catch {
129
+ }
130
+ throw new OAuthError(errorMessage, "kontext_oauth_token_exchange_failed", {
131
+ errorCode,
132
+ meta: {
133
+ integrationName,
134
+ integrationId
135
+ }
136
+ });
137
+ }
138
+ const tokenResponse = await response.json();
139
+ if (!tokenResponse.access_token) {
140
+ throw new OAuthError(
141
+ "Token exchange response missing access_token.",
142
+ "kontext_oauth_token_exchange_failed"
143
+ );
144
+ }
145
+ if (!tokenResponse.issued_token_type) {
146
+ throw new OAuthError(
147
+ "Token exchange response missing issued_token_type.",
148
+ "kontext_oauth_token_exchange_failed"
149
+ );
150
+ }
151
+ if (!tokenResponse.token_type) {
152
+ throw new OAuthError(
153
+ "Token exchange response missing token_type.",
154
+ "kontext_oauth_token_exchange_failed"
155
+ );
156
+ }
157
+ return tokenResponse;
158
+ }
159
+
160
+ // src/verify/errors.ts
161
+ var TokenVerificationError = class _TokenVerificationError extends Error {
162
+ code;
163
+ constructor(code, message) {
164
+ super(message);
165
+ this.name = "TokenVerificationError";
166
+ this.code = code;
167
+ Object.setPrototypeOf(this, _TokenVerificationError.prototype);
168
+ }
169
+ };
170
+
171
+ // src/verify/jwks-client.ts
172
+ var DEFAULT_CACHE_TTL_MS = 5 * 60 * 1e3;
173
+ var DEFAULT_REFETCH_COOLDOWN_MS = 30 * 1e3;
174
+ var JwksClient = class {
175
+ jwksUrl;
176
+ cacheTtlMs;
177
+ refetchCooldownMs;
178
+ customFetch;
179
+ jwks = null;
180
+ lastFetchAt = 0;
181
+ lastRefreshAt = 0;
182
+ constructor(options) {
183
+ this.jwksUrl = new URL(options.jwksUrl);
184
+ this.cacheTtlMs = options.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;
185
+ this.refetchCooldownMs = options.refetchCooldownMs ?? DEFAULT_REFETCH_COOLDOWN_MS;
186
+ this.customFetch = options.fetch;
187
+ }
188
+ /**
189
+ * Get the JWKS key resolver for use with jose's jwtVerify.
190
+ *
191
+ * Creates the remote JWKS on first call and caches it.
192
+ * The jose library handles internal caching and key lookup.
193
+ */
194
+ getKeyResolver() {
195
+ const now = Date.now();
196
+ if (this.jwks && now - this.lastFetchAt > this.cacheTtlMs) {
197
+ this.jwks = null;
198
+ }
199
+ if (!this.jwks) {
200
+ this.jwks = createRemoteJWKSet(this.jwksUrl, {
201
+ // jose handles caching internally, we just track our own refresh timing
202
+ ...this.customFetch && {
203
+ [/* @__PURE__ */ Symbol.for("fetch")]: this.customFetch
204
+ }
205
+ });
206
+ this.lastFetchAt = now;
207
+ }
208
+ return this.jwks;
209
+ }
210
+ /**
211
+ * Force refresh the JWKS cache.
212
+ *
213
+ * Respects the refetch cooldown to prevent rapid refetching.
214
+ * Returns true if refresh was performed, false if cooldown not elapsed.
215
+ */
216
+ refresh() {
217
+ const now = Date.now();
218
+ if (!this.canRefresh()) {
219
+ return false;
220
+ }
221
+ this.jwks = null;
222
+ this.lastRefreshAt = now;
223
+ return true;
224
+ }
225
+ /**
226
+ * Check if a refresh is allowed (cooldown elapsed).
227
+ */
228
+ canRefresh() {
229
+ return Date.now() - this.lastRefreshAt >= this.refetchCooldownMs;
230
+ }
231
+ /**
232
+ * Handle unknown kid errors by attempting refresh.
233
+ *
234
+ * @returns TokenVerificationError if refresh not allowed or already attempted
235
+ */
236
+ handleUnknownKid(kid) {
237
+ if (this.refresh()) {
238
+ return null;
239
+ }
240
+ return new TokenVerificationError(
241
+ "UNKNOWN_KID",
242
+ `Unknown key ID: ${kid}. JWKS refresh on cooldown.`
243
+ );
244
+ }
245
+ /**
246
+ * Clear the cache, forcing a fresh fetch on next access.
247
+ */
248
+ clearCache() {
249
+ this.jwks = null;
250
+ this.lastFetchAt = 0;
251
+ }
252
+ };
253
+
254
+ // src/verify/verifier.ts
255
+ var DEFAULT_CLOCK_TOLERANCE_SEC = 30;
256
+ var SUPPORTED_ALGORITHMS = ["ES256", "RS256"];
257
+ var KontextTokenVerifier = class {
258
+ config;
259
+ jwksClient;
260
+ audiences;
261
+ constructor(config) {
262
+ this.config = {
263
+ jwksUrl: config.jwksUrl,
264
+ issuer: config.issuer,
265
+ audience: config.audience,
266
+ requiredScopes: config.requiredScopes ?? [],
267
+ cacheTtlMs: config.cacheTtlMs ?? 5 * 60 * 1e3,
268
+ refetchCooldownMs: config.refetchCooldownMs ?? 30 * 1e3,
269
+ clockToleranceSec: config.clockToleranceSec ?? DEFAULT_CLOCK_TOLERANCE_SEC,
270
+ fetch: config.fetch
271
+ };
272
+ this.audiences = Array.isArray(config.audience) ? config.audience : [config.audience];
273
+ this.jwksClient = new JwksClient({
274
+ jwksUrl: config.jwksUrl,
275
+ cacheTtlMs: this.config.cacheTtlMs,
276
+ refetchCooldownMs: this.config.refetchCooldownMs,
277
+ fetch: config.fetch
278
+ });
279
+ }
280
+ /**
281
+ * Verify a JWT token.
282
+ *
283
+ * @param token - The JWT token string (without "Bearer " prefix)
284
+ * @returns VerifyResult with success=true and claims, or success=false and error
285
+ */
286
+ async verify(token) {
287
+ try {
288
+ return await this.verifyInternal(token, false);
289
+ } catch (error) {
290
+ if (error instanceof TokenVerificationError) {
291
+ return { success: false, error };
292
+ }
293
+ return {
294
+ success: false,
295
+ error: new TokenVerificationError(
296
+ "INVALID_TOKEN_FORMAT",
297
+ `Unexpected verification error: ${error.message}`
298
+ )
299
+ };
300
+ }
301
+ }
302
+ /**
303
+ * Verify a JWT token and return claims or null.
304
+ * Simpler API for cases where you don't need error details.
305
+ *
306
+ * @param token - The JWT token string (without "Bearer " prefix)
307
+ * @returns VerifiedTokenClaims if valid, null if invalid
308
+ */
309
+ async verifyOrNull(token) {
310
+ const result = await this.verify(token);
311
+ return result.success ? result.claims : null;
312
+ }
313
+ /**
314
+ * Clear the JWKS cache, forcing a fresh fetch on next verification.
315
+ */
316
+ clearCache() {
317
+ this.jwksClient.clearCache();
318
+ }
319
+ async verifyInternal(token, isRetry) {
320
+ const JWKS = this.jwksClient.getKeyResolver();
321
+ try {
322
+ const { payload, protectedHeader } = await jwtVerify(token, JWKS, {
323
+ issuer: this.config.issuer,
324
+ audience: this.audiences,
325
+ clockTolerance: this.config.clockToleranceSec,
326
+ algorithms: SUPPORTED_ALGORITHMS
327
+ });
328
+ const alg = protectedHeader.alg;
329
+ if (!SUPPORTED_ALGORITHMS.includes(alg)) {
330
+ throw new TokenVerificationError(
331
+ "UNSUPPORTED_ALGORITHM",
332
+ `Unsupported algorithm: ${alg}. Expected one of: ${SUPPORTED_ALGORITHMS.join(", ")}`
333
+ );
334
+ }
335
+ const jwtPayload = payload;
336
+ if (typeof jwtPayload.exp !== "number" || !Number.isFinite(jwtPayload.exp) || jwtPayload.exp <= 0) {
337
+ throw new TokenVerificationError(
338
+ "MISSING_CLAIMS",
339
+ "Token missing required exp claim"
340
+ );
341
+ }
342
+ const scopes = this.parseScopes(jwtPayload.scope);
343
+ for (const required of this.config.requiredScopes) {
344
+ if (!scopes.includes(required)) {
345
+ throw new TokenVerificationError(
346
+ "MISSING_SCOPE",
347
+ `Missing required scope: ${required}`
348
+ );
349
+ }
350
+ }
351
+ const clientId = jwtPayload.client_id || jwtPayload.sub;
352
+ if (!clientId) {
353
+ throw new TokenVerificationError(
354
+ "MISSING_CLAIMS",
355
+ "Token missing client_id and sub claims"
356
+ );
357
+ }
358
+ const claims = {
359
+ sub: jwtPayload.sub || "",
360
+ clientId,
361
+ scopes,
362
+ expiresAt: new Date(jwtPayload.exp * 1e3),
363
+ jti: jwtPayload.jti,
364
+ payload: jwtPayload
365
+ };
366
+ return { success: true, claims };
367
+ } catch (error) {
368
+ if (error instanceof errors.JWKSNoMatchingKey) {
369
+ if (!isRetry) {
370
+ const kid = this.extractKid(token);
371
+ const refreshError = this.jwksClient.handleUnknownKid(
372
+ kid || "unknown"
373
+ );
374
+ if (!refreshError) {
375
+ return this.verifyInternal(token, true);
376
+ }
377
+ return { success: false, error: refreshError };
378
+ }
379
+ return {
380
+ success: false,
381
+ error: new TokenVerificationError(
382
+ "UNKNOWN_KID",
383
+ "No matching key found in JWKS"
384
+ )
385
+ };
386
+ }
387
+ if (error instanceof errors.JWTExpired) {
388
+ return {
389
+ success: false,
390
+ error: new TokenVerificationError(
391
+ "TOKEN_EXPIRED",
392
+ "Token has expired"
393
+ )
394
+ };
395
+ }
396
+ if (error instanceof errors.JWTClaimValidationFailed) {
397
+ const message = error.message;
398
+ if (message.includes("iss")) {
399
+ const expected = Array.isArray(this.config.issuer) ? this.config.issuer.join(" or ") : this.config.issuer;
400
+ return {
401
+ success: false,
402
+ error: new TokenVerificationError(
403
+ "INVALID_ISSUER",
404
+ `Invalid issuer: expected ${expected}`
405
+ )
406
+ };
407
+ }
408
+ if (message.includes("aud")) {
409
+ return {
410
+ success: false,
411
+ error: new TokenVerificationError(
412
+ "INVALID_AUDIENCE",
413
+ `Invalid audience: expected one of ${this.audiences.join(", ")}`
414
+ )
415
+ };
416
+ }
417
+ if (message.includes("nbf")) {
418
+ return {
419
+ success: false,
420
+ error: new TokenVerificationError(
421
+ "TOKEN_NOT_YET_VALID",
422
+ "Token is not yet valid (nbf claim)"
423
+ )
424
+ };
425
+ }
426
+ }
427
+ if (error instanceof errors.JWSSignatureVerificationFailed) {
428
+ return {
429
+ success: false,
430
+ error: new TokenVerificationError(
431
+ "INVALID_SIGNATURE",
432
+ "Signature verification failed"
433
+ )
434
+ };
435
+ }
436
+ if (error instanceof errors.JWSInvalid) {
437
+ return {
438
+ success: false,
439
+ error: new TokenVerificationError(
440
+ "INVALID_TOKEN_FORMAT",
441
+ `Invalid JWS: ${error.message}`
442
+ )
443
+ };
444
+ }
445
+ if (error instanceof TokenVerificationError) {
446
+ throw error;
447
+ }
448
+ throw new TokenVerificationError(
449
+ "INVALID_TOKEN_FORMAT",
450
+ `Verification failed: ${error.message}`
451
+ );
452
+ }
453
+ }
454
+ parseScopes(scope) {
455
+ if (!scope) return [];
456
+ return scope.split(" ").map((s) => s.trim()).filter(Boolean);
457
+ }
458
+ extractKid(token) {
459
+ try {
460
+ const header = decodeProtectedHeader(token);
461
+ return header.kid ?? null;
462
+ } catch {
463
+ return null;
464
+ }
465
+ }
466
+ };
467
+
468
+ // src/server/sessions.ts
469
+ var SessionManager = class _SessionManager {
470
+ transports = /* @__PURE__ */ new Map();
471
+ lastAccessed = /* @__PURE__ */ new Map();
472
+ expiresAt = /* @__PURE__ */ new Map();
473
+ cleanupInterval;
474
+ static STALE_TIMEOUT_MS = 60 * 60 * 1e3;
475
+ // 1 hour
476
+ static CLEANUP_INTERVAL_MS = 5 * 60 * 1e3;
477
+ // 5 minutes
478
+ constructor() {
479
+ this.cleanupInterval = setInterval(
480
+ () => this.cleanupStaleSessions(),
481
+ _SessionManager.CLEANUP_INTERVAL_MS
482
+ );
483
+ if (this.cleanupInterval.unref) {
484
+ this.cleanupInterval.unref();
485
+ }
486
+ }
487
+ getTransport(sessionId) {
488
+ return this.transports.get(sessionId);
489
+ }
490
+ registerSession(sessionId, transport, callbacks, expiresAt) {
491
+ this.transports.set(sessionId, transport);
492
+ this.lastAccessed.set(sessionId, Date.now());
493
+ if (expiresAt !== void 0) {
494
+ this.expiresAt.set(sessionId, expiresAt);
495
+ }
496
+ transport.onclose = () => {
497
+ this.removeSession(sessionId);
498
+ callbacks?.onSessionClosed?.(sessionId);
499
+ };
500
+ }
501
+ touchSession(sessionId) {
502
+ if (this.transports.has(sessionId)) {
503
+ this.lastAccessed.set(sessionId, Date.now());
504
+ }
505
+ }
506
+ removeSession(sessionId) {
507
+ this.transports.delete(sessionId);
508
+ this.lastAccessed.delete(sessionId);
509
+ this.expiresAt.delete(sessionId);
510
+ }
511
+ /**
512
+ * Check if a session's token has expired.
513
+ * Returns true if the token's `expiresAt` has passed.
514
+ */
515
+ isSessionExpired(sessionId) {
516
+ const exp = this.expiresAt.get(sessionId);
517
+ return exp !== void 0 && Date.now() / 1e3 >= exp;
518
+ }
519
+ cleanupStaleSessions() {
520
+ const now = Date.now();
521
+ for (const [sid, lastTime] of this.lastAccessed.entries()) {
522
+ if (now - lastTime > _SessionManager.STALE_TIMEOUT_MS) {
523
+ const transport = this.transports.get(sid);
524
+ if (transport) {
525
+ void transport.close?.();
526
+ }
527
+ this.removeSession(sid);
528
+ }
529
+ }
530
+ }
531
+ destroy() {
532
+ clearInterval(this.cleanupInterval);
533
+ for (const [sid, transport] of this.transports.entries()) {
534
+ void transport.close?.();
535
+ this.removeSession(sid);
536
+ }
537
+ }
538
+ };
539
+
540
+ // src/server/kontext.ts
541
+ var DEFAULT_API_URL = "https://api.kontext.dev";
542
+ var METADATA_CACHE_TTL_MS = 60 * 60 * 1e3;
543
+ var CREDENTIAL_CACHE_MAX_ENTRIES = 500;
544
+ var RUNTIME_AUTH_CACHE_MAX_ENTRIES = 8;
545
+ var RESOLVED_CREDENTIAL_CACHE_TTL_MS = 30 * 1e3;
546
+ var SDK_VERSION = (() => {
547
+ try {
548
+ const esmRequire = createRequire(import.meta.url);
549
+ const pkg = esmRequire("../../package.json");
550
+ return pkg.version ?? "unknown";
551
+ } catch {
552
+ return "unknown";
553
+ }
554
+ })();
555
+ var Kontext = class _Kontext {
556
+ static shutdownInstances = /* @__PURE__ */ new Set();
557
+ static shutdownHandlersRegistered = false;
558
+ clientId;
559
+ clientSecret;
560
+ apiUrl;
561
+ tokenIssuers;
562
+ // AS metadata: fetched lazily, cached with TTL
563
+ oauthMetadata = null;
564
+ metadataFetchedAt = 0;
565
+ metadataPromise = null;
566
+ // Token exchange caching: keyed by `${integration}\0${subjectToken}`
567
+ credentialCache = /* @__PURE__ */ new Map();
568
+ resolvedCredentialCache = /* @__PURE__ */ new Map();
569
+ runtimeAuthCache = /* @__PURE__ */ new Map();
570
+ runtimeVerifierIds = /* @__PURE__ */ new WeakMap();
571
+ runtimeVerifierIdCounter = 0;
572
+ // Telemetry: cached service token for event reporting
573
+ serviceToken = null;
574
+ serviceTokenExp = 0;
575
+ serviceTokenPromise = null;
576
+ // Session tracking: MCP sessionId → API agentSessionId
577
+ agentSessionIds = /* @__PURE__ */ new Map();
578
+ pendingSessionDisconnects = /* @__PURE__ */ new Set();
579
+ constructor(options) {
580
+ this.clientId = options.clientId;
581
+ this.clientSecret = options.clientSecret ?? process.env.KONTEXT_CLIENT_SECRET;
582
+ this.apiUrl = (options.apiUrl ?? DEFAULT_API_URL).replace(/\/$/, "");
583
+ const rawTokenIssuers = Array.isArray(options.tokenIssuer) ? options.tokenIssuer : options.tokenIssuer ? options.tokenIssuer.split(",") : process.env.KONTEXT_TOKEN_ISSUER?.split(",");
584
+ this.tokenIssuers = Array.from(
585
+ new Set(rawTokenIssuers?.map((issuer) => issuer.trim()).filter(Boolean))
586
+ );
587
+ _Kontext.shutdownInstances.add(this);
588
+ _Kontext.ensureShutdownHandlers();
589
+ }
590
+ /**
591
+ * Cleanup method for runtimes that create/dispose SDK instances dynamically.
592
+ * Ensures this instance can be garbage-collected by removing static references.
593
+ */
594
+ async destroy() {
595
+ await this.disconnectAllSessions();
596
+ _Kontext.shutdownInstances.delete(this);
597
+ this.credentialCache.clear();
598
+ this.resolvedCredentialCache.clear();
599
+ this.oauthMetadata = null;
600
+ this.metadataFetchedAt = 0;
601
+ this.metadataPromise = null;
602
+ this.serviceToken = null;
603
+ this.serviceTokenExp = 0;
604
+ this.serviceTokenPromise = null;
605
+ this.agentSessionIds.clear();
606
+ this.pendingSessionDisconnects.clear();
607
+ }
608
+ static ensureShutdownHandlers() {
609
+ if (_Kontext.shutdownHandlersRegistered) return;
610
+ const onShutdown = () => {
611
+ for (const instance of _Kontext.shutdownInstances) {
612
+ void instance.disconnectAllSessions();
613
+ }
614
+ };
615
+ process.once("SIGINT", onShutdown);
616
+ process.once("SIGTERM", onShutdown);
617
+ _Kontext.shutdownHandlersRegistered = true;
618
+ }
619
+ // ===========================================================================
620
+ // middleware()
621
+ // ===========================================================================
622
+ /**
623
+ * Express middleware: `.well-known` metadata + bearer auth + MCP transport + sessions.
624
+ *
625
+ * Must be mounted at the app root (not a sub-path) because RFC 9728 requires
626
+ * `/.well-known/oauth-protected-resource` at the root. Use `mcpPath` to set
627
+ * the transport endpoint path.
628
+ *
629
+ * @param server - An `McpServer` instance for single-session use, or a
630
+ * `() => McpServer` factory for concurrent sessions (recommended in production).
631
+ * `McpServer.connect()` is 1:1 per the MCP spec — passing a factory ensures
632
+ * each session gets its own instance.
633
+ *
634
+ * @example Factory pattern (recommended for concurrent sessions)
635
+ * ```typescript
636
+ * app.use(kontext.middleware(() => createServer()));
637
+ * ```
638
+ *
639
+ * @example Single instance (local dev / single session)
640
+ * ```typescript
641
+ * app.use(kontext.middleware(server));
642
+ * ```
643
+ *
644
+ * @example Custom path
645
+ * ```typescript
646
+ * app.use(kontext.middleware(createServer, { mcpPath: "/api/mcp" }));
647
+ * ```
648
+ */
649
+ middleware(server, options) {
650
+ const esmRequire = createRequire(import.meta.url);
651
+ const express = esmRequire("express");
652
+ const router = express.Router();
653
+ const mcpPath = options?.mcpPath ?? "/mcp";
654
+ const sessionManager = new SessionManager();
655
+ const omitAuth = options?.dangerouslyOmitAuth ?? false;
656
+ router.use((_req, res, next) => {
657
+ res.header("Access-Control-Allow-Origin", "*");
658
+ res.header(
659
+ "Access-Control-Allow-Headers",
660
+ "Content-Type, Authorization, Mcp-Session-Id, Mcp-Protocol-Version, Accept"
661
+ );
662
+ res.header("Access-Control-Expose-Headers", "Mcp-Session-Id");
663
+ res.header("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
664
+ if (_req.method === "OPTIONS") {
665
+ res.sendStatus(204);
666
+ return;
667
+ }
668
+ next();
669
+ });
670
+ if (omitAuth) {
671
+ console.warn(
672
+ "[kontext] \u26A0\uFE0F Auth is disabled (dangerouslyOmitAuth). Do NOT use in production."
673
+ );
674
+ router.use(mcpPath, express.json({ limit: options?.bodyLimit ?? "1mb" }));
675
+ const mcpHandler2 = this.createMcpHandler(
676
+ server,
677
+ sessionManager,
678
+ null,
679
+ options
680
+ );
681
+ router.post(mcpPath, mcpHandler2.post);
682
+ router.get(mcpPath, mcpHandler2.get);
683
+ router.delete(mcpPath, mcpHandler2.delete);
684
+ return router;
685
+ }
686
+ const getRuntimeAuth = async (req) => {
687
+ const metadata = this.applyMetadataTransform(
688
+ await this.getOAuthMetadata(),
689
+ options?.metadataTransform
690
+ );
691
+ const rsUrl = this.resolveResourceServerUrl(req, mcpPath, options);
692
+ return this.getOrCreateRuntimeAuthContext(
693
+ metadata,
694
+ rsUrl,
695
+ options?.verifier
696
+ );
697
+ };
698
+ router.use(async (req, res, next) => {
699
+ const path = req.path || req.url || "";
700
+ const isMetadataRequest = path.startsWith("/.well-known/oauth-authorization-server") || path.startsWith("/.well-known/oauth-protected-resource");
701
+ if (!isMetadataRequest) {
702
+ next();
703
+ return;
704
+ }
705
+ try {
706
+ const runtimeAuth = await getRuntimeAuth(req);
707
+ runtimeAuth.metadataRouter(req, res, next);
708
+ } catch (error) {
709
+ this.respondMetadataInitError(res, error);
710
+ }
711
+ });
712
+ router.use(mcpPath, express.json({ limit: options?.bodyLimit ?? "1mb" }));
713
+ const mcpHandler = this.createMcpHandler(
714
+ server,
715
+ sessionManager,
716
+ getRuntimeAuth,
717
+ options
718
+ );
719
+ router.post(mcpPath, mcpHandler.post);
720
+ router.get(mcpPath, mcpHandler.get);
721
+ router.delete(mcpPath, mcpHandler.delete);
722
+ return router;
723
+ }
724
+ // ===========================================================================
725
+ // require()
726
+ // ===========================================================================
727
+ /**
728
+ * Exchange a user's access token for an integration credential.
729
+ *
730
+ * @param integration - Integration name (e.g., "github")
731
+ * @param token - The user's Bearer token (from `authInfo.token`)
732
+ * @returns Integration credential with `accessToken` and `authorization` header
733
+ *
734
+ * @throws {IntegrationConnectionRequiredError} User hasn't connected this integration
735
+ * @throws {OAuthError} Token exchange failed
736
+ */
737
+ async require(integration, token) {
738
+ const now = Date.now();
739
+ this.evictExpiredCredentials(now);
740
+ const cacheKey = `${integration}\0${token}`;
741
+ const cached = this.credentialCache.get(cacheKey);
742
+ if (cached && now < cached.expiresAt) {
743
+ this.credentialCache.delete(cacheKey);
744
+ this.credentialCache.set(cacheKey, cached);
745
+ return cached.credential;
746
+ }
747
+ if (cached) {
748
+ this.credentialCache.delete(cacheKey);
749
+ }
750
+ const exchangeConfig = {
751
+ tokenUrl: `${this.apiUrl}/oauth2/token`,
752
+ clientId: this.clientId,
753
+ clientSecret: this.clientSecret
754
+ };
755
+ let response;
756
+ try {
757
+ response = await exchangeToken(exchangeConfig, token, integration);
758
+ } catch (err) {
759
+ if (err instanceof OAuthError) {
760
+ if (err.errorCode === "integration_required" || err.message.includes("not connected") || err.message.includes("expired") && err.message.includes("reconnect")) {
761
+ const integrationId = err.meta.integrationId || integration;
762
+ const connectUrl = await this.fetchConnectUrl(
763
+ token,
764
+ integrationId,
765
+ exchangeConfig
766
+ );
767
+ throw new IntegrationConnectionRequiredError(integrationId, {
768
+ integrationName: err.meta.integrationName,
769
+ connectUrl,
770
+ message: err.message
771
+ });
772
+ }
773
+ }
774
+ throw err;
775
+ }
776
+ const credential = {
777
+ accessToken: response.access_token,
778
+ tokenType: response.token_type,
779
+ authorization: `${response.token_type} ${response.access_token}`,
780
+ expiresIn: response.expires_in,
781
+ scope: response.scope,
782
+ integration
783
+ };
784
+ if (response.expires_in) {
785
+ const ttlMs = Math.min(response.expires_in - 60, 5 * 60) * 1e3;
786
+ if (ttlMs > 0) {
787
+ this.trimCacheToFit(this.credentialCache, CREDENTIAL_CACHE_MAX_ENTRIES);
788
+ this.credentialCache.set(cacheKey, {
789
+ credential,
790
+ expiresAt: now + ttlMs
791
+ });
792
+ }
793
+ }
794
+ return credential;
795
+ }
796
+ /**
797
+ * Resolve per-user credential key/value pairs for an internal MCP integration.
798
+ *
799
+ * @param integration - Integration UUID or name
800
+ * @param token - The user's Bearer token (from `authInfo.token`)
801
+ * @returns Decrypted credential map for the current user and integration
802
+ *
803
+ * @throws {IntegrationConnectionRequiredError} User has not provided required credentials
804
+ * @throws {OAuthError} Runtime credential resolution failed
805
+ */
806
+ async requireCredentials(integration, token) {
807
+ const now = Date.now();
808
+ this.evictExpiredResolvedCredentials(now);
809
+ const cacheKey = `${integration}\0${token}\0internal_credentials`;
810
+ const cached = this.resolvedCredentialCache.get(cacheKey);
811
+ if (cached && now < cached.expiresAt) {
812
+ this.resolvedCredentialCache.delete(cacheKey);
813
+ this.resolvedCredentialCache.set(cacheKey, cached);
814
+ return cached.credential;
815
+ }
816
+ if (cached) {
817
+ this.resolvedCredentialCache.delete(cacheKey);
818
+ }
819
+ const exchangeConfig = {
820
+ tokenUrl: `${this.apiUrl}/oauth2/token`,
821
+ clientId: this.clientId,
822
+ clientSecret: this.clientSecret
823
+ };
824
+ let gatewayAccessToken = token;
825
+ if (!this.isGatewayScopedToken(token)) {
826
+ try {
827
+ const exchanged = await exchangeToken(
828
+ exchangeConfig,
829
+ token,
830
+ "mcp-gateway"
831
+ );
832
+ gatewayAccessToken = exchanged.access_token;
833
+ } catch (err) {
834
+ throw new OAuthError(
835
+ "Failed to exchange subject token for runtime",
836
+ "kontext_credentials_exchange_failed",
837
+ {
838
+ errorCode: "credentials_exchange_failed",
839
+ errorDescription: err instanceof Error ? err.message : String(err ?? "unknown error")
840
+ }
841
+ );
842
+ }
843
+ }
844
+ const integrationId = await this.resolveRuntimeIntegrationId(
845
+ integration,
846
+ gatewayAccessToken
847
+ );
848
+ const res = await fetch(
849
+ `${this.apiUrl}/mcp/integrations/${integrationId}/credentials/resolve`,
850
+ {
851
+ method: "POST",
852
+ headers: {
853
+ Authorization: `Bearer ${gatewayAccessToken}`,
854
+ "Content-Type": "application/json"
855
+ },
856
+ body: "{}"
857
+ }
858
+ );
859
+ if (!res.ok) {
860
+ const text = await res.text().catch(() => "");
861
+ const message = text && text.trim().length > 0 ? text : `HTTP ${res.status} while resolving credentials`;
862
+ if (res.status === 400 && message.toLowerCase().includes("credentials required")) {
863
+ throw new IntegrationConnectionRequiredError(integrationId, {
864
+ integrationName: String(integration),
865
+ message
866
+ });
867
+ }
868
+ throw new OAuthError(
869
+ `Failed to resolve credentials for integration ${integrationId}`,
870
+ "kontext_credentials_resolve_failed",
871
+ {
872
+ errorCode: "credentials_resolve_failed",
873
+ errorDescription: message
874
+ }
875
+ );
876
+ }
877
+ const payload = await res.json();
878
+ if (!payload.credentials || typeof payload.credentials !== "object" || Array.isArray(payload.credentials)) {
879
+ throw new OAuthError(
880
+ "Credential resolve returned invalid payload",
881
+ "kontext_credentials_invalid_payload"
882
+ );
883
+ }
884
+ const credentials = {};
885
+ for (const [key, value] of Object.entries(payload.credentials)) {
886
+ if (typeof value === "string") {
887
+ credentials[key] = value;
888
+ }
889
+ }
890
+ if (Object.keys(credentials).length === 0) {
891
+ throw new IntegrationConnectionRequiredError(integrationId, {
892
+ integrationName: String(integration),
893
+ message: "No credentials configured for this integration"
894
+ });
895
+ }
896
+ const resolved = {
897
+ integration,
898
+ integrationId: payload.integrationId ?? integrationId,
899
+ credentials
900
+ };
901
+ this.trimCacheToFit(
902
+ this.resolvedCredentialCache,
903
+ CREDENTIAL_CACHE_MAX_ENTRIES
904
+ );
905
+ this.resolvedCredentialCache.set(cacheKey, {
906
+ credential: resolved,
907
+ expiresAt: now + RESOLVED_CREDENTIAL_CACHE_TTL_MS
908
+ });
909
+ return resolved;
910
+ }
911
+ getGatewayAudiences() {
912
+ return /* @__PURE__ */ new Set([`${new URL(this.apiUrl).origin}/mcp`, "mcp-gateway"]);
913
+ }
914
+ isGatewayScopedToken(token) {
915
+ const audiences = this.extractTokenAudiences(token);
916
+ if (audiences.length === 0) {
917
+ return false;
918
+ }
919
+ const gatewayAudiences = this.getGatewayAudiences();
920
+ return audiences.some((audience) => gatewayAudiences.has(audience));
921
+ }
922
+ extractTokenAudiences(token) {
923
+ const [, payloadPart] = token.split(".");
924
+ if (!payloadPart) return [];
925
+ try {
926
+ const payload = JSON.parse(
927
+ Buffer.from(payloadPart, "base64url").toString("utf8")
928
+ );
929
+ if (typeof payload.aud === "string") {
930
+ return [payload.aud];
931
+ }
932
+ if (Array.isArray(payload.aud)) {
933
+ return payload.aud.filter(
934
+ (value) => typeof value === "string"
935
+ );
936
+ }
937
+ } catch {
938
+ }
939
+ return [];
940
+ }
941
+ // ===========================================================================
942
+ // Private: fetch connect URL (spec §2 — two-step init)
943
+ // ===========================================================================
944
+ async resolveRuntimeIntegrationId(integration, runtimeToken) {
945
+ const raw = String(integration);
946
+ if (this.isUuid(raw)) {
947
+ return raw;
948
+ }
949
+ const res = await fetch(`${this.apiUrl}/mcp/integrations`, {
950
+ headers: {
951
+ Authorization: `Bearer ${runtimeToken}`
952
+ }
953
+ });
954
+ if (!res.ok) {
955
+ const text = await res.text().catch(() => "");
956
+ throw new OAuthError(
957
+ "Failed to resolve integration identifier",
958
+ "kontext_integration_lookup_failed",
959
+ {
960
+ errorCode: "integration_lookup_failed",
961
+ errorDescription: text || `HTTP ${res.status}`
962
+ }
963
+ );
964
+ }
965
+ const payload = await res.json();
966
+ const items = Array.isArray(payload.items) ? payload.items : [];
967
+ const match = items.find((item) => item.id === raw || item.name === raw);
968
+ const integrationId = match?.id;
969
+ if (!integrationId) {
970
+ throw new IntegrationConnectionRequiredError(raw, {
971
+ integrationName: raw,
972
+ message: `Integration ${raw} is not attached to this application`
973
+ });
974
+ }
975
+ return integrationId;
976
+ }
977
+ isUuid(value) {
978
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
979
+ value
980
+ );
981
+ }
982
+ /**
983
+ * Fetch a browser-openable connect URL for a missing integration.
984
+ *
985
+ * Per the integration-interrupt-flow spec, the SDK:
986
+ * 1. Exchanges the user's token for a resource-scoped mcp-gateway JWT
987
+ * 2. Calls POST /mcp/integrations/:id/oauth/init with that JWT
988
+ * 3. Returns the `connectUrl` (intermediate endpoint with one-time token)
989
+ *
990
+ * The connect URL points to our own server (ticket pattern), which
991
+ * validates the ticket, sets a browser session cookie, then redirects
992
+ * to the actual OAuth provider.
993
+ */
994
+ async fetchConnectUrl(subjectToken, integrationId, exchangeConfig) {
995
+ try {
996
+ const gatewayToken = await exchangeToken(
997
+ exchangeConfig,
998
+ subjectToken,
999
+ "mcp-gateway"
1000
+ );
1001
+ const initUrl = `${this.apiUrl}/mcp/integrations/${integrationId}/oauth/init`;
1002
+ const res = await fetch(initUrl, {
1003
+ method: "POST",
1004
+ headers: {
1005
+ Authorization: `Bearer ${gatewayToken.access_token}`,
1006
+ "Content-Type": "application/json"
1007
+ },
1008
+ body: JSON.stringify({})
1009
+ });
1010
+ if (!res.ok) {
1011
+ const text = await res.text().catch(() => "");
1012
+ console.warn(
1013
+ `[kontext] fetchConnectUrl: init endpoint returned ${res.status}: ${text}`
1014
+ );
1015
+ return void 0;
1016
+ }
1017
+ const data = await res.json();
1018
+ return data.connectUrl ?? data.authorizationUrl;
1019
+ } catch (err) {
1020
+ console.warn(
1021
+ `[kontext] fetchConnectUrl failed:`,
1022
+ err instanceof Error ? err.message : String(err)
1023
+ );
1024
+ return void 0;
1025
+ }
1026
+ }
1027
+ // ===========================================================================
1028
+ // Private: AS metadata
1029
+ // ===========================================================================
1030
+ async getOAuthMetadata() {
1031
+ const now = Date.now();
1032
+ if (this.oauthMetadata && now - this.metadataFetchedAt < METADATA_CACHE_TTL_MS) {
1033
+ return this.oauthMetadata;
1034
+ }
1035
+ if (this.metadataPromise) {
1036
+ return this.metadataPromise;
1037
+ }
1038
+ this.metadataPromise = this.fetchOAuthMetadata();
1039
+ try {
1040
+ const metadata = await this.metadataPromise;
1041
+ this.oauthMetadata = metadata;
1042
+ this.metadataFetchedAt = Date.now();
1043
+ return metadata;
1044
+ } finally {
1045
+ this.metadataPromise = null;
1046
+ }
1047
+ }
1048
+ applyMetadataTransform(metadata, metadataTransform) {
1049
+ if (!metadataTransform) {
1050
+ return metadata;
1051
+ }
1052
+ return metadataTransform(this.cloneOAuthMetadata(metadata));
1053
+ }
1054
+ cloneOAuthMetadata(metadata) {
1055
+ return JSON.parse(JSON.stringify(metadata));
1056
+ }
1057
+ async fetchOAuthMetadata() {
1058
+ const urls = [
1059
+ `${this.apiUrl}/.well-known/oauth-authorization-server`,
1060
+ `${this.apiUrl}/.well-known/openid-configuration`
1061
+ ];
1062
+ let lastError;
1063
+ for (const url of urls) {
1064
+ try {
1065
+ const res = await fetch(url);
1066
+ if (res.ok) {
1067
+ return await res.json();
1068
+ }
1069
+ } catch (err) {
1070
+ lastError = err instanceof Error ? err : new Error(String(err));
1071
+ }
1072
+ }
1073
+ throw new Error(
1074
+ `Failed to fetch AS metadata from ${this.apiUrl}: ${lastError?.message ?? "unknown error"}`
1075
+ );
1076
+ }
1077
+ resolveResourceServerUrl(req, mcpPath, options) {
1078
+ if (options?.resourceServerUrl) {
1079
+ return new URL(options.resourceServerUrl);
1080
+ }
1081
+ const host = req.get("host");
1082
+ if (!host) {
1083
+ throw new Error(
1084
+ "Missing Host header. Set middleware({ resourceServerUrl }) to a trusted public URL."
1085
+ );
1086
+ }
1087
+ return new URL(`${req.protocol}://${host}${mcpPath}`);
1088
+ }
1089
+ getOrCreateRuntimeAuthContext(metadata, rsUrl, customVerifier) {
1090
+ const key = this.getRuntimeAuthCacheKey(rsUrl, customVerifier);
1091
+ const cached = this.runtimeAuthCache.get(key);
1092
+ if (cached) {
1093
+ this.runtimeAuthCache.delete(key);
1094
+ this.runtimeAuthCache.set(key, cached);
1095
+ return cached;
1096
+ }
1097
+ const proxiedMetadata = { ...metadata, issuer: `${rsUrl.origin}/` };
1098
+ const metadataRouter = mcpAuthMetadataRouter({
1099
+ oauthMetadata: proxiedMetadata,
1100
+ resourceServerUrl: rsUrl
1101
+ });
1102
+ const resourceMetadataUrl = getOAuthProtectedResourceMetadataUrl(rsUrl);
1103
+ const verifier = customVerifier ?? this.createTokenVerifier(metadata, rsUrl);
1104
+ const runtimeAuth = {
1105
+ metadataRouter,
1106
+ bearerAuth: requireBearerAuth({
1107
+ verifier,
1108
+ resourceMetadataUrl
1109
+ })
1110
+ };
1111
+ this.trimCacheToFit(this.runtimeAuthCache, RUNTIME_AUTH_CACHE_MAX_ENTRIES);
1112
+ this.runtimeAuthCache.set(key, runtimeAuth);
1113
+ return runtimeAuth;
1114
+ }
1115
+ getRuntimeAuthCacheKey(rsUrl, customVerifier) {
1116
+ if (!customVerifier) {
1117
+ return `${rsUrl.href}\0default`;
1118
+ }
1119
+ let verifierId = this.runtimeVerifierIds.get(customVerifier);
1120
+ if (verifierId === void 0) {
1121
+ verifierId = ++this.runtimeVerifierIdCounter;
1122
+ this.runtimeVerifierIds.set(customVerifier, verifierId);
1123
+ }
1124
+ return `${rsUrl.href}\0custom:${verifierId}`;
1125
+ }
1126
+ respondMetadataInitError(res, error) {
1127
+ const message = error instanceof Error ? error.message : String(error);
1128
+ console.error(`[kontext] Failed to fetch AS metadata: ${message}`);
1129
+ if (res.headersSent) return;
1130
+ res.status(503).json({
1131
+ error: "service_unavailable",
1132
+ error_description: "Failed to fetch authorization server metadata. Retry later."
1133
+ });
1134
+ }
1135
+ evictExpiredCredentials(now) {
1136
+ for (const [key, value] of this.credentialCache.entries()) {
1137
+ if (value.expiresAt <= now) {
1138
+ this.credentialCache.delete(key);
1139
+ }
1140
+ }
1141
+ }
1142
+ evictExpiredResolvedCredentials(now) {
1143
+ for (const [key, value] of this.resolvedCredentialCache.entries()) {
1144
+ if (value.expiresAt <= now) {
1145
+ this.resolvedCredentialCache.delete(key);
1146
+ }
1147
+ }
1148
+ }
1149
+ trimCacheToFit(cache, maxEntries) {
1150
+ while (cache.size >= maxEntries) {
1151
+ const oldestKey = cache.keys().next().value;
1152
+ if (!oldestKey) break;
1153
+ cache.delete(oldestKey);
1154
+ }
1155
+ }
1156
+ // ===========================================================================
1157
+ // Private: token verifier
1158
+ // ===========================================================================
1159
+ createTokenVerifier(metadata, resourceUrl) {
1160
+ const metadataRaw = metadata;
1161
+ const jwksUri = metadataRaw.jwks_uri ?? `${this.apiUrl}/.well-known/jwks.json`;
1162
+ const clientId = this.clientId;
1163
+ const issuers = Array.from(
1164
+ new Set(
1165
+ [metadata.issuer, ...this.tokenIssuers].filter(
1166
+ (issuer2) => typeof issuer2 === "string" && !!issuer2
1167
+ )
1168
+ )
1169
+ );
1170
+ if (!issuers.length) {
1171
+ throw new Error("OAuth metadata missing issuer");
1172
+ }
1173
+ const issuer = issuers.length === 1 ? issuers[0] : issuers;
1174
+ const verifier = new KontextTokenVerifier({
1175
+ jwksUrl: jwksUri,
1176
+ issuer,
1177
+ audience: resourceUrl.href
1178
+ });
1179
+ return {
1180
+ async verifyAccessToken(token) {
1181
+ const result = await verifier.verify(token);
1182
+ if (!result.success) {
1183
+ throw new InvalidTokenError(
1184
+ `Token verification failed: ${result.error.message}`
1185
+ );
1186
+ }
1187
+ const { claims } = result;
1188
+ const payload = claims.payload;
1189
+ const ext = payload.ext ?? {};
1190
+ return {
1191
+ token,
1192
+ clientId: claims.clientId ?? clientId,
1193
+ scopes: claims.scopes,
1194
+ expiresAt: Math.floor(claims.expiresAt.getTime() / 1e3),
1195
+ extra: {
1196
+ ...ext,
1197
+ sub: claims.sub,
1198
+ email: payload.email ?? ext.email
1199
+ }
1200
+ };
1201
+ }
1202
+ };
1203
+ }
1204
+ // ===========================================================================
1205
+ // Private: telemetry
1206
+ // ===========================================================================
1207
+ async getServiceToken() {
1208
+ if (this.serviceToken && Date.now() < this.serviceTokenExp - 3e4) {
1209
+ return this.serviceToken;
1210
+ }
1211
+ if (this.serviceTokenPromise) {
1212
+ return this.serviceTokenPromise;
1213
+ }
1214
+ this.serviceTokenPromise = (async () => {
1215
+ const res = await fetch(`${this.apiUrl}/oauth2/token`, {
1216
+ method: "POST",
1217
+ headers: {
1218
+ "Content-Type": "application/x-www-form-urlencoded",
1219
+ Authorization: `Basic ${Buffer.from(this.clientId + ":" + this.clientSecret).toString("base64")}`
1220
+ },
1221
+ body: "grant_type=client_credentials"
1222
+ });
1223
+ if (!res.ok) {
1224
+ const text = await res.text().catch(() => "");
1225
+ throw new Error(
1226
+ `[kontext:telemetry] client_credentials grant failed: HTTP ${res.status} ${text}`
1227
+ );
1228
+ }
1229
+ const data = await res.json();
1230
+ this.serviceToken = data.access_token;
1231
+ this.serviceTokenExp = Date.now() + data.expires_in * 1e3;
1232
+ return data.access_token;
1233
+ })();
1234
+ try {
1235
+ return await this.serviceTokenPromise;
1236
+ } finally {
1237
+ this.serviceTokenPromise = null;
1238
+ }
1239
+ }
1240
+ reportEvent(event) {
1241
+ if (!this.clientSecret || !event.sessionId) return;
1242
+ this.getServiceToken().then(
1243
+ (token) => fetch(`${this.apiUrl}/api/v1/mcp-events`, {
1244
+ method: "POST",
1245
+ headers: {
1246
+ "Content-Type": "application/json",
1247
+ Authorization: `Bearer ${token}`
1248
+ },
1249
+ body: JSON.stringify({
1250
+ ...event,
1251
+ agentId: this.clientId,
1252
+ clientId: this.clientId,
1253
+ clientVersion: SDK_VERSION
1254
+ })
1255
+ }).then((res) => {
1256
+ if (!res.ok) {
1257
+ console.warn(
1258
+ `[kontext:telemetry] event report failed: HTTP ${res.status}`
1259
+ );
1260
+ }
1261
+ })
1262
+ ).catch((err) => {
1263
+ console.warn(
1264
+ `[kontext:telemetry] error:`,
1265
+ err instanceof Error ? err.message : String(err)
1266
+ );
1267
+ });
1268
+ }
1269
+ // ===========================================================================
1270
+ // Private: session lifecycle
1271
+ // ===========================================================================
1272
+ createAgentSession(userToken, mcpSessionId, metadata) {
1273
+ if (!this.clientSecret || !userToken) return;
1274
+ const tokenIdentifier = createHash("sha256").update(userToken).digest("hex");
1275
+ this.getServiceToken().then(
1276
+ (token) => fetch(`${this.apiUrl}/api/v1/agent-sessions`, {
1277
+ method: "POST",
1278
+ headers: {
1279
+ "Content-Type": "application/json",
1280
+ Authorization: `Bearer ${token}`
1281
+ },
1282
+ body: JSON.stringify({
1283
+ tokenIdentifier,
1284
+ hostname: metadata?.hostname,
1285
+ userAgent: metadata?.userAgent,
1286
+ clientInfo: metadata?.clientInfo,
1287
+ tokenExpiresAt: metadata?.tokenExpiresAt ? new Date(metadata.tokenExpiresAt * 1e3).toISOString() : void 0
1288
+ })
1289
+ }).then(async (res) => {
1290
+ if (res.ok) {
1291
+ const data = await res.json();
1292
+ if (this.pendingSessionDisconnects.delete(mcpSessionId)) {
1293
+ this.disconnectAgentSessionByAgentSessionId(
1294
+ data.sessionId,
1295
+ token
1296
+ );
1297
+ return;
1298
+ }
1299
+ this.agentSessionIds.set(mcpSessionId, data.sessionId);
1300
+ } else {
1301
+ this.pendingSessionDisconnects.delete(mcpSessionId);
1302
+ console.warn(
1303
+ `[kontext:sessions] create failed: HTTP ${res.status}`
1304
+ );
1305
+ }
1306
+ })
1307
+ ).catch((err) => {
1308
+ this.pendingSessionDisconnects.delete(mcpSessionId);
1309
+ console.warn(
1310
+ `[kontext:sessions] error:`,
1311
+ err instanceof Error ? err.message : String(err)
1312
+ );
1313
+ });
1314
+ }
1315
+ disconnectAgentSessionByAgentSessionId(agentSessionId, serviceToken) {
1316
+ if (!this.clientSecret) return;
1317
+ const tokenPromise = serviceToken ? Promise.resolve(serviceToken) : this.getServiceToken();
1318
+ tokenPromise.then(
1319
+ (token) => fetch(
1320
+ `${this.apiUrl}/api/v1/agent-sessions/${agentSessionId}/disconnect`,
1321
+ {
1322
+ method: "POST",
1323
+ headers: { Authorization: `Bearer ${token}` }
1324
+ }
1325
+ )
1326
+ ).catch(() => {
1327
+ });
1328
+ }
1329
+ disconnectAgentSession(mcpSessionId) {
1330
+ if (!this.clientSecret) return;
1331
+ const agentSessionId = this.agentSessionIds.get(mcpSessionId);
1332
+ this.agentSessionIds.delete(mcpSessionId);
1333
+ if (!agentSessionId) {
1334
+ this.pendingSessionDisconnects.add(mcpSessionId);
1335
+ return;
1336
+ }
1337
+ this.pendingSessionDisconnects.delete(mcpSessionId);
1338
+ this.disconnectAgentSessionByAgentSessionId(agentSessionId);
1339
+ }
1340
+ async disconnectAllSessions() {
1341
+ if (!this.clientSecret) return;
1342
+ if (this.agentSessionIds.size === 0) {
1343
+ this.pendingSessionDisconnects.clear();
1344
+ return;
1345
+ }
1346
+ try {
1347
+ const token = await this.getServiceToken();
1348
+ await Promise.allSettled(
1349
+ [...this.agentSessionIds.values()].map(
1350
+ (agentSessionId) => fetch(
1351
+ `${this.apiUrl}/api/v1/agent-sessions/${agentSessionId}/disconnect`,
1352
+ {
1353
+ method: "POST",
1354
+ headers: { Authorization: `Bearer ${token}` }
1355
+ }
1356
+ )
1357
+ )
1358
+ );
1359
+ } catch {
1360
+ }
1361
+ this.agentSessionIds.clear();
1362
+ this.pendingSessionDisconnects.clear();
1363
+ }
1364
+ // ===========================================================================
1365
+ // Private: MCP transport handlers
1366
+ // ===========================================================================
1367
+ async runBearerAuth(bearerAuth, req, res) {
1368
+ await new Promise((resolve, reject) => {
1369
+ let settled = false;
1370
+ let nextCalled = false;
1371
+ const cleanup = () => {
1372
+ res.removeListener("finish", onResponseDone);
1373
+ res.removeListener("close", onResponseDone);
1374
+ };
1375
+ const settleResolve = () => {
1376
+ if (settled) return;
1377
+ settled = true;
1378
+ cleanup();
1379
+ resolve();
1380
+ };
1381
+ const settleReject = (err) => {
1382
+ if (settled) return;
1383
+ settled = true;
1384
+ cleanup();
1385
+ reject(err instanceof Error ? err : new Error(String(err)));
1386
+ };
1387
+ const onResponseDone = () => {
1388
+ settleResolve();
1389
+ };
1390
+ res.once("finish", onResponseDone);
1391
+ res.once("close", onResponseDone);
1392
+ let middlewareResult;
1393
+ try {
1394
+ middlewareResult = bearerAuth(req, res, (err) => {
1395
+ nextCalled = true;
1396
+ if (err) {
1397
+ settleReject(err);
1398
+ return;
1399
+ }
1400
+ settleResolve();
1401
+ });
1402
+ } catch (err) {
1403
+ settleReject(err);
1404
+ return;
1405
+ }
1406
+ void Promise.resolve(middlewareResult).then(
1407
+ () => {
1408
+ if (!nextCalled && res.headersSent) {
1409
+ settleResolve();
1410
+ }
1411
+ },
1412
+ (err) => {
1413
+ settleReject(err);
1414
+ }
1415
+ );
1416
+ });
1417
+ }
1418
+ createMcpHandler(server, sessionManager, getRuntimeAuth, options) {
1419
+ const callbacks = {
1420
+ onSessionClosed: (sessionId) => {
1421
+ options?.onSessionClosed?.(sessionId);
1422
+ this.disconnectAgentSession(sessionId);
1423
+ }
1424
+ };
1425
+ const post = async (req, res) => {
1426
+ const traceId = crypto.randomUUID();
1427
+ const authReq = req;
1428
+ if (getRuntimeAuth) {
1429
+ let bearerAuth;
1430
+ try {
1431
+ const runtimeAuth = await getRuntimeAuth(req);
1432
+ bearerAuth = runtimeAuth.bearerAuth;
1433
+ } catch (error) {
1434
+ this.respondMetadataInitError(res, error);
1435
+ return;
1436
+ }
1437
+ await this.runBearerAuth(bearerAuth, req, res);
1438
+ const sessionId2 = req.headers["mcp-session-id"];
1439
+ if (sessionId2) {
1440
+ if (res.headersSent) {
1441
+ this.reportEvent({
1442
+ eventType: "auth_error",
1443
+ traceId,
1444
+ sessionId: sessionId2,
1445
+ durationMs: 0,
1446
+ status: "error_auth"
1447
+ });
1448
+ return;
1449
+ }
1450
+ if (authReq.auth) {
1451
+ this.reportEvent({
1452
+ eventType: "auth_ok",
1453
+ traceId,
1454
+ ownerUserId: authReq.auth.extra?.sub,
1455
+ sessionId: sessionId2,
1456
+ durationMs: 0,
1457
+ status: "ok"
1458
+ });
1459
+ }
1460
+ } else if (res.headersSent) {
1461
+ return;
1462
+ }
1463
+ }
1464
+ const sessionId = req.headers["mcp-session-id"];
1465
+ if (sessionId) {
1466
+ const transport2 = sessionManager.getTransport(sessionId);
1467
+ if (transport2) {
1468
+ sessionManager.touchSession(sessionId);
1469
+ await transport2.handleRequest(req, res, req.body);
1470
+ return;
1471
+ }
1472
+ }
1473
+ if (!isInitializeRequest(req.body)) {
1474
+ res.status(400).json({
1475
+ jsonrpc: "2.0",
1476
+ error: {
1477
+ code: -32e3,
1478
+ message: sessionId ? `Session ${sessionId} not found` : "No valid session ID provided"
1479
+ },
1480
+ id: null
1481
+ });
1482
+ return;
1483
+ }
1484
+ const authInfo = authReq.auth;
1485
+ const transport = new StreamableHTTPServerTransport({
1486
+ sessionIdGenerator: () => crypto.randomUUID(),
1487
+ onsessioninitialized: (sid) => {
1488
+ sessionManager.registerSession(
1489
+ sid,
1490
+ transport,
1491
+ callbacks,
1492
+ authInfo?.expiresAt
1493
+ );
1494
+ options?.onSessionInitialized?.(sid, authInfo, transport);
1495
+ this.reportEvent({
1496
+ eventType: "initialize",
1497
+ traceId,
1498
+ sessionId: sid,
1499
+ ownerUserId: authInfo?.extra?.sub,
1500
+ durationMs: 0,
1501
+ status: "ok"
1502
+ });
1503
+ this.createAgentSession(authInfo?.token, sid, {
1504
+ hostname: req.headers["x-forwarded-for"],
1505
+ userAgent: req.headers["user-agent"],
1506
+ tokenExpiresAt: authInfo?.expiresAt
1507
+ });
1508
+ }
1509
+ });
1510
+ const originalHandle = transport.handleRequest.bind(transport);
1511
+ transport.handleRequest = async (wrappedReq, wrappedRes, parsedBody) => {
1512
+ const reqTraceId = wrappedReq === req ? traceId : crypto.randomUUID();
1513
+ const sid = wrappedReq.headers["mcp-session-id"] ?? transport.sessionId;
1514
+ const start = Date.now();
1515
+ try {
1516
+ await originalHandle(wrappedReq, wrappedRes, parsedBody);
1517
+ if (parsedBody?.method === "tools/call") {
1518
+ this.reportEvent({
1519
+ eventType: "execute_tool",
1520
+ traceId: reqTraceId,
1521
+ toolName: parsedBody.params?.name,
1522
+ durationMs: Date.now() - start,
1523
+ sessionId: sid,
1524
+ ownerUserId: authInfo?.extra?.sub,
1525
+ status: "ok",
1526
+ requestJson: parsedBody.params
1527
+ });
1528
+ } else if (parsedBody?.method === "tools/list") {
1529
+ this.reportEvent({
1530
+ eventType: "search_tools",
1531
+ traceId: reqTraceId,
1532
+ durationMs: Date.now() - start,
1533
+ sessionId: sid,
1534
+ ownerUserId: authInfo?.extra?.sub,
1535
+ status: "ok"
1536
+ });
1537
+ }
1538
+ } catch (err) {
1539
+ if (parsedBody?.method === "tools/call") {
1540
+ this.reportEvent({
1541
+ eventType: "execute_tool",
1542
+ traceId: reqTraceId,
1543
+ toolName: parsedBody.params?.name,
1544
+ durationMs: Date.now() - start,
1545
+ sessionId: sid,
1546
+ ownerUserId: authInfo?.extra?.sub,
1547
+ status: "error_remote",
1548
+ errorMessage: err instanceof Error ? err.message : String(err)
1549
+ });
1550
+ } else if (parsedBody?.method === "tools/list") {
1551
+ this.reportEvent({
1552
+ eventType: "search_tools",
1553
+ traceId: reqTraceId,
1554
+ durationMs: Date.now() - start,
1555
+ sessionId: sid,
1556
+ ownerUserId: authInfo?.extra?.sub,
1557
+ status: "error_remote",
1558
+ errorMessage: err instanceof Error ? err.message : String(err)
1559
+ });
1560
+ }
1561
+ throw err;
1562
+ }
1563
+ };
1564
+ const mcpServer = typeof server === "function" ? server() : server;
1565
+ await mcpServer.connect(transport);
1566
+ await transport.handleRequest(req, res, req.body);
1567
+ };
1568
+ const get = async (req, res) => {
1569
+ if (getRuntimeAuth) {
1570
+ let bearerAuth;
1571
+ try {
1572
+ const runtimeAuth = await getRuntimeAuth(req);
1573
+ bearerAuth = runtimeAuth.bearerAuth;
1574
+ } catch (error) {
1575
+ this.respondMetadataInitError(res, error);
1576
+ return;
1577
+ }
1578
+ await this.runBearerAuth(bearerAuth, req, res);
1579
+ if (res.headersSent) {
1580
+ return;
1581
+ }
1582
+ }
1583
+ const sessionId = req.headers["mcp-session-id"] || req.headers["Mcp-Session-Id"];
1584
+ if (!sessionId) {
1585
+ res.status(400).json({ error: "Missing Mcp-Session-Id header" });
1586
+ return;
1587
+ }
1588
+ const transport = sessionManager.getTransport(sessionId);
1589
+ if (!transport) {
1590
+ res.status(400).json({ error: "Session not found" });
1591
+ return;
1592
+ }
1593
+ sessionManager.touchSession(sessionId);
1594
+ await transport.handleRequest(req, res);
1595
+ };
1596
+ const del = async (req, res) => {
1597
+ if (getRuntimeAuth) {
1598
+ let bearerAuth;
1599
+ try {
1600
+ const runtimeAuth = await getRuntimeAuth(req);
1601
+ bearerAuth = runtimeAuth.bearerAuth;
1602
+ } catch (error) {
1603
+ this.respondMetadataInitError(res, error);
1604
+ return;
1605
+ }
1606
+ await this.runBearerAuth(bearerAuth, req, res);
1607
+ if (res.headersSent) {
1608
+ return;
1609
+ }
1610
+ }
1611
+ const sessionId = req.headers["mcp-session-id"] || req.headers["Mcp-Session-Id"];
1612
+ if (!sessionId) {
1613
+ res.status(400).json({ error: "Missing Mcp-Session-Id header" });
1614
+ return;
1615
+ }
1616
+ const transport = sessionManager.getTransport(sessionId);
1617
+ if (!transport) {
1618
+ res.status(400).json({ error: "Session not found" });
1619
+ return;
1620
+ }
1621
+ await transport.handleRequest(req, res);
1622
+ };
1623
+ return { post, get, delete: del };
1624
+ }
1625
+ };
1626
+
1627
+ export { IntegrationConnectionRequiredError, Kontext, KontextTokenVerifier };
1628
+ //# sourceMappingURL=index.js.map
1629
+ //# sourceMappingURL=index.js.map