@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
package/dist/index.cjs ADDED
@@ -0,0 +1,4046 @@
1
+ 'use strict';
2
+
3
+ var index_js = require('@modelcontextprotocol/sdk/client/index.js');
4
+ var streamableHttp_js$1 = require('@modelcontextprotocol/sdk/client/streamableHttp.js');
5
+ var types_js = require('@modelcontextprotocol/sdk/types.js');
6
+ var crypto$1 = require('crypto');
7
+ var module$1 = require('module');
8
+ var streamableHttp_js = require('@modelcontextprotocol/sdk/server/streamableHttp.js');
9
+ var router_js = require('@modelcontextprotocol/sdk/server/auth/router.js');
10
+ var bearerAuth_js = require('@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js');
11
+ var errors_js = require('@modelcontextprotocol/sdk/server/auth/errors.js');
12
+ var jose = require('jose');
13
+
14
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
15
+ // src/mcp/client.ts
16
+
17
+ // src/storage/memory.ts
18
+ var MemoryStorage = class {
19
+ store = /* @__PURE__ */ new Map();
20
+ async getJson(key) {
21
+ const value = this.store.get(key);
22
+ if (value === void 0) {
23
+ return void 0;
24
+ }
25
+ return JSON.parse(JSON.stringify(value));
26
+ }
27
+ async setJson(key, value) {
28
+ if (value === void 0) {
29
+ this.store.delete(key);
30
+ } else {
31
+ this.store.set(key, JSON.parse(JSON.stringify(value)));
32
+ }
33
+ }
34
+ /**
35
+ * Clear all stored data
36
+ */
37
+ clear() {
38
+ this.store.clear();
39
+ }
40
+ /**
41
+ * Get the number of stored items
42
+ */
43
+ get size() {
44
+ return this.store.size;
45
+ }
46
+ /**
47
+ * Check if a key exists
48
+ */
49
+ has(key) {
50
+ return this.store.has(key);
51
+ }
52
+ /**
53
+ * Get all keys (useful for debugging)
54
+ */
55
+ keys() {
56
+ return Array.from(this.store.keys());
57
+ }
58
+ };
59
+
60
+ // src/storage/types.ts
61
+ function createStorageKey(applicationClientId, sessionKey, ...parts) {
62
+ const namespace = sessionKey ? `kontext:${applicationClientId}:${sessionKey}` : `kontext:${applicationClientId}`;
63
+ return [namespace, ...parts].join(":");
64
+ }
65
+ var StorageKeys = {
66
+ // Existing keys
67
+ TOKENS: "tokens",
68
+ CODE_VERIFIER: "code_verifier",
69
+ STATE: "state",
70
+ // Pattern B (RFC 8693 Token Exchange) keys
71
+ /** Identity tokens (no audience) */
72
+ IDENTITY_TOKENS: "identity_tokens",
73
+ /** Prefix for resource-scoped tokens */
74
+ RESOURCE_TOKENS: "resource_tokens"
75
+ };
76
+ function resourceTokenKey(resource) {
77
+ return `${StorageKeys.RESOURCE_TOKENS}:${resource}`;
78
+ }
79
+
80
+ // src/errors.ts
81
+ var KontextError = class extends Error {
82
+ /** Brand field for type narrowing without instanceof */
83
+ kontextError = true;
84
+ /** Machine-readable error code, always prefixed with `kontext_` */
85
+ code;
86
+ /** HTTP status code when applicable */
87
+ statusCode;
88
+ /** Auto-generated link to error documentation */
89
+ docsUrl;
90
+ /** Server request ID for debugging / support escalation */
91
+ requestId;
92
+ /** Contextual metadata bag (integration IDs, param names, etc.) */
93
+ meta;
94
+ constructor(message, code, options) {
95
+ super(message, { cause: options?.cause });
96
+ this.name = "KontextError";
97
+ this.code = code;
98
+ this.statusCode = options?.statusCode;
99
+ this.requestId = options?.requestId;
100
+ this.meta = options?.meta ?? {};
101
+ this.docsUrl = `https://docs.kontext.dev/errors/${code}`;
102
+ Object.setPrototypeOf(this, new.target.prototype);
103
+ }
104
+ toJSON() {
105
+ return {
106
+ name: this.name,
107
+ code: this.code,
108
+ message: this.message,
109
+ statusCode: this.statusCode,
110
+ docsUrl: this.docsUrl,
111
+ requestId: this.requestId,
112
+ meta: Object.keys(this.meta).length > 0 ? this.meta : void 0
113
+ };
114
+ }
115
+ toString() {
116
+ const parts = [`[${this.code}] ${this.message}`];
117
+ if (this.docsUrl) parts.push(`Docs: ${this.docsUrl}`);
118
+ if (this.requestId) parts.push(`Request ID: ${this.requestId}`);
119
+ return parts.join("\n");
120
+ }
121
+ };
122
+ function isKontextError(err) {
123
+ return typeof err === "object" && err !== null && err.kontextError === true;
124
+ }
125
+ var AuthorizationRequiredError = class extends KontextError {
126
+ authorizationUrl;
127
+ constructor(message = "Authorization required. Complete the OAuth flow to continue.", options) {
128
+ super(message, "kontext_authorization_required", {
129
+ statusCode: 401,
130
+ ...options
131
+ });
132
+ this.name = "AuthorizationRequiredError";
133
+ this.authorizationUrl = options?.authorizationUrl;
134
+ }
135
+ };
136
+ var OAuthError = class extends KontextError {
137
+ errorCode;
138
+ errorDescription;
139
+ constructor(message, code, options) {
140
+ super(message, code, {
141
+ statusCode: options?.statusCode ?? 400,
142
+ ...options
143
+ });
144
+ this.name = "OAuthError";
145
+ this.errorCode = options?.errorCode;
146
+ this.errorDescription = options?.errorDescription;
147
+ }
148
+ };
149
+ var IntegrationConnectionRequiredError = class extends KontextError {
150
+ integrationId;
151
+ integrationName;
152
+ connectUrl;
153
+ constructor(integrationId, options) {
154
+ super(
155
+ options?.message ?? `Connection to integration "${integrationId}" is required. Visit the connect URL to authorize.`,
156
+ "kontext_integration_connection_required",
157
+ { statusCode: 403, ...options }
158
+ );
159
+ this.name = "IntegrationConnectionRequiredError";
160
+ this.integrationId = integrationId;
161
+ this.integrationName = options?.integrationName;
162
+ this.connectUrl = options?.connectUrl;
163
+ }
164
+ };
165
+ var ConfigError = class extends KontextError {
166
+ constructor(message, code, options) {
167
+ super(message, code, options);
168
+ this.name = "ConfigError";
169
+ }
170
+ };
171
+ var NetworkError = class extends KontextError {
172
+ constructor(message = "Network error. Check your internet connection and that the server is reachable.", options) {
173
+ super(message, "kontext_network_error", options);
174
+ this.name = "NetworkError";
175
+ }
176
+ };
177
+ var HttpError = class extends KontextError {
178
+ retryAfter;
179
+ validationErrors;
180
+ constructor(message, code, options) {
181
+ super(message, code, {
182
+ statusCode: options?.statusCode,
183
+ ...options
184
+ });
185
+ this.name = "HttpError";
186
+ this.retryAfter = options?.retryAfter;
187
+ this.validationErrors = options?.validationErrors;
188
+ }
189
+ };
190
+ function errorProps(err) {
191
+ return err;
192
+ }
193
+ var NETWORK_ERROR_CODES = /* @__PURE__ */ new Set([
194
+ "ECONNREFUSED",
195
+ "ENOTFOUND",
196
+ "ETIMEDOUT",
197
+ "ECONNRESET",
198
+ "ECONNABORTED",
199
+ "EPIPE",
200
+ "UND_ERR_CONNECT_TIMEOUT"
201
+ ]);
202
+ function isNetworkError(err) {
203
+ if (err.name === "AbortError") return true;
204
+ const props = errorProps(err);
205
+ const sysCode = props.code;
206
+ if (typeof sysCode === "string" && NETWORK_ERROR_CODES.has(sysCode))
207
+ return true;
208
+ if (err.name === "TypeError" && err.cause instanceof Error) {
209
+ const causeCode = errorProps(err.cause).code;
210
+ if (typeof causeCode === "string" && NETWORK_ERROR_CODES.has(causeCode))
211
+ return true;
212
+ }
213
+ return false;
214
+ }
215
+ function isUnauthorizedError(err) {
216
+ const props = errorProps(err);
217
+ if (props.statusCode === 401 || props.status === 401) return true;
218
+ if (err.name === "UnauthorizedError") return true;
219
+ if (err.message === "Unauthorized") return true;
220
+ return false;
221
+ }
222
+ function parseHttpError(statusCode, body) {
223
+ const message = typeof body === "object" && body !== null && "message" in body ? String(body.message) : `HTTP ${statusCode}`;
224
+ const errorCode = typeof body === "object" && body !== null && "code" in body ? String(body.code) : void 0;
225
+ switch (statusCode) {
226
+ case 400:
227
+ if (typeof body === "object" && body !== null && "errors" in body && Array.isArray(body.errors)) {
228
+ return new HttpError(message, "kontext_validation_error", {
229
+ statusCode: 400,
230
+ validationErrors: body.errors
231
+ });
232
+ }
233
+ return new KontextError(message, errorCode ?? "kontext_bad_request", {
234
+ statusCode: 400
235
+ });
236
+ case 401:
237
+ return new AuthorizationRequiredError(message);
238
+ case 403:
239
+ if (errorCode === "INTEGRATION_CONNECTION_REQUIRED") {
240
+ const details = body;
241
+ return new IntegrationConnectionRequiredError(
242
+ details.integrationId ?? "unknown",
243
+ {
244
+ integrationName: details.integrationName,
245
+ connectUrl: details.connectUrl,
246
+ message
247
+ }
248
+ );
249
+ }
250
+ return new HttpError(message, "kontext_policy_denied", {
251
+ statusCode: 403,
252
+ meta: { policy: body?.policy }
253
+ });
254
+ case 404:
255
+ return new HttpError(message, "kontext_not_found", { statusCode: 404 });
256
+ case 429: {
257
+ const retryAfter = typeof body === "object" && body !== null && "retryAfter" in body ? Number(body.retryAfter) : void 0;
258
+ return new HttpError(
259
+ retryAfter ? `Rate limit exceeded. Retry after ${retryAfter} seconds.` : "Rate limit exceeded. Wait and retry.",
260
+ "kontext_rate_limited",
261
+ { statusCode: 429, retryAfter }
262
+ );
263
+ }
264
+ default:
265
+ if (statusCode >= 500) {
266
+ return new HttpError(
267
+ `Server error (HTTP ${statusCode}): ${message}`,
268
+ "kontext_server_error",
269
+ { statusCode }
270
+ );
271
+ }
272
+ return new KontextError(message, errorCode ?? "kontext_unknown_error", {
273
+ statusCode
274
+ });
275
+ }
276
+ }
277
+
278
+ // src/oauth/provider.ts
279
+ var KontextOAuthProvider = class {
280
+ config;
281
+ storagePrefix;
282
+ pendingState = null;
283
+ expiryBufferMs = 60 * 1e3;
284
+ constructor(config) {
285
+ this.config = config;
286
+ this.storagePrefix = createStorageKey(config.clientId, config.sessionKey);
287
+ }
288
+ /**
289
+ * The redirect URL for OAuth callbacks
290
+ */
291
+ get redirectUrl() {
292
+ return this.config.redirectUri;
293
+ }
294
+ /**
295
+ * OAuth client metadata
296
+ */
297
+ get clientMetadata() {
298
+ return {
299
+ redirect_uris: [this.config.redirectUri],
300
+ client_name: this.config.clientName,
301
+ grant_types: ["authorization_code", "refresh_token"],
302
+ response_types: ["code"],
303
+ token_endpoint_auth_method: "none"
304
+ // Public client
305
+ };
306
+ }
307
+ /**
308
+ * Generate a random state parameter for OAuth CSRF protection
309
+ */
310
+ state() {
311
+ const array = new Uint8Array(32);
312
+ if (globalThis.crypto?.getRandomValues) {
313
+ globalThis.crypto.getRandomValues(array);
314
+ } else {
315
+ array.set(crypto$1.randomBytes(32));
316
+ }
317
+ const state = Array.from(
318
+ array,
319
+ (byte) => byte.toString(16).padStart(2, "0")
320
+ ).join("");
321
+ this.pendingState = state;
322
+ void this.config.storage.setJson(
323
+ this.getStorageKey(StorageKeys.STATE),
324
+ state
325
+ );
326
+ return state;
327
+ }
328
+ /**
329
+ * Returns the client information (client_id)
330
+ * Since we're a public client with pre-registered credentials,
331
+ * we don't use dynamic client registration.
332
+ */
333
+ async clientInformation() {
334
+ return {
335
+ client_id: this.config.clientId
336
+ };
337
+ }
338
+ /**
339
+ * Load stored OAuth tokens
340
+ */
341
+ async tokens() {
342
+ const key = this.getStorageKey(StorageKeys.TOKENS);
343
+ return this.config.storage.getJson(key);
344
+ }
345
+ /**
346
+ * Save OAuth tokens after successful authorization
347
+ */
348
+ async saveTokens(tokens) {
349
+ const key = this.getStorageKey(StorageKeys.TOKENS);
350
+ await this.config.storage.setJson(key, this.withIssuedAt(tokens));
351
+ }
352
+ /**
353
+ * Redirect the user agent to the authorization URL
354
+ */
355
+ async redirectToAuthorization(authorizationUrl) {
356
+ await this.config.onRedirectToAuthorization(authorizationUrl);
357
+ }
358
+ /**
359
+ * Save the PKCE code verifier before redirecting to authorization
360
+ */
361
+ async saveCodeVerifier(codeVerifier) {
362
+ const key = this.getStorageKey(StorageKeys.CODE_VERIFIER);
363
+ await this.config.storage.setJson(key, codeVerifier);
364
+ }
365
+ /**
366
+ * Load the PKCE code verifier for token exchange
367
+ */
368
+ async codeVerifier() {
369
+ const key = this.getStorageKey(StorageKeys.CODE_VERIFIER);
370
+ const verifier = await this.config.storage.getJson(key);
371
+ if (!verifier) {
372
+ throw new OAuthError(
373
+ "No PKCE code verifier found in storage. The OAuth flow may have expired or storage was cleared. Restart the auth flow.",
374
+ "kontext_oauth_code_verifier_missing"
375
+ );
376
+ }
377
+ return verifier;
378
+ }
379
+ /**
380
+ * Invalidate stored credentials
381
+ */
382
+ async invalidateCredentials(scope) {
383
+ if (scope === "all" || scope === "tokens") {
384
+ const tokensKey = this.getStorageKey(StorageKeys.TOKENS);
385
+ await this.config.storage.setJson(tokensKey, void 0);
386
+ const identityKey = this.getStorageKey(StorageKeys.IDENTITY_TOKENS);
387
+ await this.config.storage.setJson(identityKey, void 0);
388
+ }
389
+ if (scope === "all" || scope === "verifier") {
390
+ const verifierKey = this.getStorageKey(StorageKeys.CODE_VERIFIER);
391
+ await this.config.storage.setJson(verifierKey, void 0);
392
+ }
393
+ if (scope === "all") {
394
+ this.pendingState = null;
395
+ const stateKey = this.getStorageKey(StorageKeys.STATE);
396
+ await this.config.storage.setJson(stateKey, void 0);
397
+ }
398
+ }
399
+ /**
400
+ * Clear all stored state (tokens, verifier, etc.)
401
+ * Call this to force re-authentication
402
+ */
403
+ async clearAll() {
404
+ await this.invalidateCredentials("all");
405
+ }
406
+ /**
407
+ * Check if we have valid (non-expired) tokens
408
+ */
409
+ async hasValidTokens() {
410
+ const storedTokens = await this.tokens();
411
+ return this.isTokenValid(storedTokens);
412
+ }
413
+ // ==========================================================================
414
+ // Pattern B: Identity and Resource Token Management (RFC 8693)
415
+ // ==========================================================================
416
+ /**
417
+ * Save identity tokens (no audience)
418
+ * These are the tokens obtained from the initial OAuth flow before token exchange.
419
+ */
420
+ async saveIdentityTokens(tokens) {
421
+ const key = this.getStorageKey(StorageKeys.IDENTITY_TOKENS);
422
+ await this.config.storage.setJson(key, this.withIssuedAt(tokens));
423
+ }
424
+ /**
425
+ * Load identity tokens
426
+ * Returns the identity tokens obtained from the initial OAuth flow.
427
+ */
428
+ async identityTokens() {
429
+ const key = this.getStorageKey(StorageKeys.IDENTITY_TOKENS);
430
+ return this.config.storage.getJson(key);
431
+ }
432
+ /**
433
+ * Save resource-scoped tokens for a specific resource
434
+ *
435
+ * @param resource The resource identifier (e.g., "mcp-gateway")
436
+ * @param tokens The resource-scoped tokens
437
+ */
438
+ async saveResourceTokens(resource, tokens) {
439
+ const key = this.getStorageKey(resourceTokenKey(resource));
440
+ await this.config.storage.setJson(key, this.withIssuedAt(tokens));
441
+ }
442
+ /**
443
+ * Load resource-scoped tokens for a specific resource
444
+ *
445
+ * @param resource The resource identifier (e.g., "mcp-gateway")
446
+ * @returns The resource-scoped tokens, or undefined if not found
447
+ */
448
+ async resourceTokens(resource) {
449
+ const key = this.getStorageKey(resourceTokenKey(resource));
450
+ return this.config.storage.getJson(key);
451
+ }
452
+ /**
453
+ * Clear resource tokens for a specific resource
454
+ *
455
+ * @param resource The resource identifier (e.g., "mcp-gateway")
456
+ */
457
+ async clearResourceTokens(resource) {
458
+ const key = this.getStorageKey(resourceTokenKey(resource));
459
+ await this.config.storage.setJson(key, void 0);
460
+ }
461
+ /**
462
+ * Check if we have valid identity tokens
463
+ */
464
+ async hasValidIdentityTokens() {
465
+ const tokens = await this.identityTokens();
466
+ return this.isTokenValid(tokens);
467
+ }
468
+ /**
469
+ * Check if we have valid resource tokens for a specific resource
470
+ *
471
+ * @param resource The resource identifier
472
+ */
473
+ async hasValidResourceTokens(resource) {
474
+ const tokens = await this.resourceTokens(resource);
475
+ return this.isTokenValid(tokens);
476
+ }
477
+ async validateState(state) {
478
+ if (!state) {
479
+ return false;
480
+ }
481
+ const key = this.getStorageKey(StorageKeys.STATE);
482
+ const storedState = this.pendingState ?? await this.config.storage.getJson(key);
483
+ const isValid = storedState === state;
484
+ if (isValid) {
485
+ this.pendingState = null;
486
+ await this.config.storage.setJson(key, void 0);
487
+ }
488
+ return isValid;
489
+ }
490
+ withIssuedAt(tokens) {
491
+ if (!tokens.expires_in) {
492
+ return tokens;
493
+ }
494
+ return { ...tokens, issued_at: Date.now() };
495
+ }
496
+ isTokenValid(tokens) {
497
+ if (!tokens?.access_token) {
498
+ return false;
499
+ }
500
+ if (!tokens.expires_in) {
501
+ return true;
502
+ }
503
+ const issuedAt = tokens.issued_at;
504
+ if (!issuedAt) {
505
+ return true;
506
+ }
507
+ const expiresAt = issuedAt + tokens.expires_in * 1e3;
508
+ return Date.now() < expiresAt - this.expiryBufferMs;
509
+ }
510
+ getStorageKey(key) {
511
+ return `${this.storagePrefix}:${key}`;
512
+ }
513
+ };
514
+ function parseOAuthCallback(callbackUrl) {
515
+ const url = typeof callbackUrl === "string" ? new URL(callbackUrl) : callbackUrl;
516
+ const params = url.searchParams;
517
+ const error = params.get("error");
518
+ if (error) {
519
+ return {
520
+ error,
521
+ errorDescription: params.get("error_description") ?? void 0
522
+ };
523
+ }
524
+ return {
525
+ code: params.get("code") ?? void 0,
526
+ state: params.get("state") ?? void 0
527
+ };
528
+ }
529
+
530
+ // src/mcp/client.ts
531
+ var DEFAULT_SERVER = "https://api.kontext.dev";
532
+ function normalizeKontextServerUrl(server) {
533
+ let url = server.replace(/\/$/, "");
534
+ url = url.replace(/\/api\/v1\/?$/, "").replace(/\/mcp\/?$/, "");
535
+ url = url.replace(/\/$/, "");
536
+ return url;
537
+ }
538
+ var KontextMcp = class {
539
+ config;
540
+ storage;
541
+ oauthProvider;
542
+ transport = null;
543
+ client = null;
544
+ _isConnected = false;
545
+ _pendingConnect = null;
546
+ _pendingAuthFlow = null;
547
+ _authFlowResolve = null;
548
+ constructor(config) {
549
+ this.config = config;
550
+ this.storage = config.storage ?? new MemoryStorage();
551
+ this.oauthProvider = new KontextOAuthProvider({
552
+ clientId: config.clientId,
553
+ redirectUri: config.redirectUri,
554
+ storage: this.storage,
555
+ sessionKey: config.sessionKey ?? "default",
556
+ clientName: config.clientName,
557
+ onRedirectToAuthorization: async (url) => {
558
+ this._pendingAuthFlow = new Promise((resolve) => {
559
+ this._authFlowResolve = resolve;
560
+ });
561
+ const result = await config.onAuthRequired(url);
562
+ if (result) {
563
+ await this.handleCallback(result);
564
+ }
565
+ }
566
+ });
567
+ }
568
+ /**
569
+ * Check if we're currently connected
570
+ */
571
+ get isConnected() {
572
+ return this._isConnected;
573
+ }
574
+ /**
575
+ * Get the underlying MCP client for advanced usage
576
+ */
577
+ get mcpClient() {
578
+ return this.client;
579
+ }
580
+ /**
581
+ * Get the session ID from the transport
582
+ */
583
+ get sessionId() {
584
+ return this.transport?.sessionId;
585
+ }
586
+ /**
587
+ * Get the server base URL
588
+ */
589
+ get serverUrl() {
590
+ return normalizeKontextServerUrl(this.config.server ?? DEFAULT_SERVER);
591
+ }
592
+ /**
593
+ * Get the MCP endpoint URL.
594
+ * When `url` is provided, use it directly. Otherwise derive from server.
595
+ */
596
+ get mcpEndpointUrl() {
597
+ return this.config.url ?? `${this.serverUrl}/mcp`;
598
+ }
599
+ /**
600
+ * List available tools from the server
601
+ *
602
+ * This will automatically handle authentication if needed.
603
+ */
604
+ async listTools() {
605
+ await this.ensureConnected();
606
+ const response = await this.client.listTools();
607
+ return response.tools;
608
+ }
609
+ /**
610
+ * Call a tool
611
+ *
612
+ * This will automatically handle authentication if needed.
613
+ *
614
+ * @param name The tool name
615
+ * @param args The tool arguments
616
+ */
617
+ async callTool(name, args) {
618
+ await this.ensureConnected();
619
+ try {
620
+ const result = await this.client.callTool({
621
+ name,
622
+ arguments: args
623
+ });
624
+ return result;
625
+ } catch (error) {
626
+ if (error instanceof types_js.UrlElicitationRequiredError && this.config.onElicitationUrl) {
627
+ for (const elicitation of error.elicitations) {
628
+ await this.config.onElicitationUrl({
629
+ url: elicitation.url,
630
+ message: elicitation.message ?? "Action required",
631
+ elicitationId: elicitation.elicitationId ?? "",
632
+ integrationId: elicitation.integrationId,
633
+ integrationName: elicitation.integrationName
634
+ });
635
+ }
636
+ }
637
+ throw error;
638
+ }
639
+ }
640
+ /**
641
+ * Create a connect session for the hosted connect UI.
642
+ *
643
+ * Returns a URL that can be opened in a browser to let the user
644
+ * connect integrations proactively (before hitting -32042 errors).
645
+ */
646
+ async createConnectSession() {
647
+ const tokens = await this.oauthProvider.tokens();
648
+ if (!tokens?.access_token) {
649
+ throw new AuthorizationRequiredError(
650
+ "Authorization required. Complete the OAuth flow first."
651
+ );
652
+ }
653
+ const response = await fetch(`${this.serverUrl}/mcp/connect-session`, {
654
+ method: "POST",
655
+ headers: {
656
+ Authorization: `Bearer ${tokens.access_token}`,
657
+ "Content-Type": "application/json"
658
+ }
659
+ });
660
+ if (response.status === 401) {
661
+ throw new AuthorizationRequiredError(
662
+ "Access token expired or invalid. Re-authenticate and retry."
663
+ );
664
+ }
665
+ if (!response.ok) {
666
+ throw new KontextError(
667
+ `Failed to create connect session: HTTP ${response.status}`,
668
+ "kontext_connect_session_failed",
669
+ { statusCode: response.status }
670
+ );
671
+ }
672
+ return await response.json();
673
+ }
674
+ /**
675
+ * List integrations attached to the current application/runtime identity.
676
+ *
677
+ * This is used by higher-level orchestrators to discover mixed integration
678
+ * topologies (gateway + internal credential integrations).
679
+ */
680
+ async listRuntimeIntegrations() {
681
+ const tokens = await this.oauthProvider.tokens();
682
+ if (!tokens?.access_token) {
683
+ throw new AuthorizationRequiredError(
684
+ "Authorization required. Complete the OAuth flow first."
685
+ );
686
+ }
687
+ const response = await fetch(`${this.serverUrl}/mcp/integrations`, {
688
+ method: "GET",
689
+ headers: {
690
+ Authorization: `Bearer ${tokens.access_token}`
691
+ }
692
+ });
693
+ if (response.status === 401) {
694
+ throw new AuthorizationRequiredError(
695
+ "Access token expired or invalid. Re-authenticate and retry."
696
+ );
697
+ }
698
+ if (!response.ok) {
699
+ throw new KontextError(
700
+ `Failed to list runtime integrations: HTTP ${response.status}`,
701
+ "kontext_runtime_integrations_failed",
702
+ { statusCode: response.status }
703
+ );
704
+ }
705
+ const payload = await response.json();
706
+ const items = Array.isArray(payload?.items) ? payload.items : [];
707
+ return items.map((item) => {
708
+ const id = typeof item.id === "string" ? item.id : "";
709
+ const name = typeof item.name === "string" ? item.name : id;
710
+ const url = typeof item.url === "string" ? item.url : "";
711
+ if (!id || !url) return null;
712
+ const category = item.category === "internal_mcp_credentials" ? "internal_mcp_credentials" : "gateway_remote_mcp";
713
+ const connectType = item.connectType === "credentials" || item.connectType === "oauth" || item.connectType === "none" ? item.connectType : category === "internal_mcp_credentials" ? "credentials" : item.authMode === "oauth" ? "oauth" : "none";
714
+ const rawConnection = item.connection && typeof item.connection === "object" ? item.connection : void 0;
715
+ const connected = rawConnection && typeof rawConnection.connected === "boolean" ? rawConnection.connected : false;
716
+ const status = rawConnection?.status === "connected" ? "connected" : "disconnected";
717
+ return {
718
+ id,
719
+ name,
720
+ url,
721
+ category,
722
+ connectType,
723
+ authMode: item.authMode === "oauth" || item.authMode === "user_token" || item.authMode === "server_token" || item.authMode === "none" ? item.authMode : void 0,
724
+ credentialSchema: item.credentialSchema,
725
+ requiresOauth: typeof item.requiresOauth === "boolean" ? item.requiresOauth : void 0,
726
+ connection: rawConnection ? {
727
+ connected,
728
+ status,
729
+ expiresAt: typeof rawConnection.expiresAt === "string" ? rawConnection.expiresAt : void 0,
730
+ displayName: typeof rawConnection.displayName === "string" ? rawConnection.displayName : void 0
731
+ } : void 0
732
+ };
733
+ }).filter((item) => item !== null);
734
+ }
735
+ /**
736
+ * Handle an OAuth callback URL
737
+ *
738
+ * Call this after the user has been redirected back from authorization.
739
+ * This is required for web apps where `onAuthRequired` redirects instead of waiting.
740
+ *
741
+ * @param callbackUrl The full callback URL with query parameters
742
+ */
743
+ async handleCallback(callbackUrl) {
744
+ const { code, state, error, errorDescription } = parseOAuthCallback(callbackUrl);
745
+ if (error) {
746
+ this._authFlowResolve?.();
747
+ this._authFlowResolve = null;
748
+ throw new AuthorizationRequiredError(
749
+ errorDescription ?? `OAuth error: ${error}`
750
+ );
751
+ }
752
+ const isValidState = await this.oauthProvider.validateState(state);
753
+ if (!isValidState) {
754
+ this._authFlowResolve?.();
755
+ this._authFlowResolve = null;
756
+ throw new OAuthError(
757
+ "OAuth state validation failed. The state parameter did not match. Retry the authorization flow.",
758
+ "kontext_oauth_state_invalid"
759
+ );
760
+ }
761
+ if (!code) {
762
+ this._authFlowResolve?.();
763
+ this._authFlowResolve = null;
764
+ throw new AuthorizationRequiredError(
765
+ "No authorization code in callback URL"
766
+ );
767
+ }
768
+ try {
769
+ if (!this.transport) {
770
+ this.transport = new streamableHttp_js$1.StreamableHTTPClientTransport(
771
+ new URL(this.mcpEndpointUrl),
772
+ {
773
+ authProvider: this.oauthProvider
774
+ }
775
+ );
776
+ }
777
+ await this.transport.finishAuth(code);
778
+ const tokens = await this.oauthProvider.tokens();
779
+ if (!tokens?.access_token) {
780
+ throw new AuthorizationRequiredError("Failed to obtain tokens");
781
+ }
782
+ await this.oauthProvider.saveTokens(tokens);
783
+ } finally {
784
+ this._authFlowResolve?.();
785
+ this._authFlowResolve = null;
786
+ }
787
+ }
788
+ /**
789
+ * Disconnect from the server
790
+ */
791
+ async disconnect() {
792
+ try {
793
+ if (this.transport) {
794
+ try {
795
+ await this.transport.terminateSession();
796
+ } catch {
797
+ }
798
+ await this.transport.close();
799
+ }
800
+ } finally {
801
+ this.transport = null;
802
+ this.client = null;
803
+ this._isConnected = false;
804
+ }
805
+ }
806
+ /**
807
+ * Clear stored tokens and require re-authentication
808
+ */
809
+ async clearAuth() {
810
+ await this.oauthProvider.clearAll();
811
+ await this.disconnect();
812
+ }
813
+ /**
814
+ * Check if this URL is an OAuth callback
815
+ *
816
+ * Useful for web apps to detect if the current URL is a callback.
817
+ *
818
+ * @param url The URL to check
819
+ */
820
+ isCallback(url) {
821
+ const urlObj = typeof url === "string" ? new URL(url) : url;
822
+ const redirectUri = new URL(this.config.redirectUri);
823
+ return urlObj.pathname === redirectUri.pathname && (urlObj.searchParams.has("code") || urlObj.searchParams.has("error"));
824
+ }
825
+ /**
826
+ * Ensure we're connected, handling auth if needed
827
+ */
828
+ async ensureConnected() {
829
+ if (this._isConnected && this.client) {
830
+ return;
831
+ }
832
+ if (this._pendingConnect) {
833
+ await this._pendingConnect;
834
+ return;
835
+ }
836
+ this._pendingConnect = this.doConnect();
837
+ try {
838
+ await this._pendingConnect;
839
+ } finally {
840
+ this._pendingConnect = null;
841
+ }
842
+ }
843
+ /**
844
+ * Internal connection logic
845
+ */
846
+ async doConnect(authRetryCount = 0) {
847
+ if (!this.transport) {
848
+ this.transport = new streamableHttp_js$1.StreamableHTTPClientTransport(
849
+ new URL(this.mcpEndpointUrl),
850
+ {
851
+ authProvider: this.oauthProvider
852
+ }
853
+ );
854
+ }
855
+ const capabilities = {
856
+ tools: {}
857
+ };
858
+ if (this.config.onElicitationUrl) {
859
+ capabilities.elicitation = { url: {} };
860
+ }
861
+ this.client = new index_js.Client(
862
+ {
863
+ name: this.config.clientName ?? "kontext-sdk",
864
+ version: this.config.clientVersion ?? "0.0.1"
865
+ },
866
+ { capabilities }
867
+ );
868
+ if (this.config.onElicitationUrl) {
869
+ const onElicitationUrl = this.config.onElicitationUrl;
870
+ this.client.setRequestHandler(types_js.ElicitRequestSchema, async (request) => {
871
+ const params = request.params;
872
+ if (params.mode === "url" && "url" in params) {
873
+ await onElicitationUrl({
874
+ url: params.url,
875
+ message: params.message ?? "Action required",
876
+ elicitationId: params.elicitationId ?? "",
877
+ integrationId: params.integrationId,
878
+ integrationName: params.integrationName
879
+ });
880
+ }
881
+ return { action: "accept" };
882
+ });
883
+ this.client.setNotificationHandler(
884
+ types_js.ElicitationCompleteNotificationSchema,
885
+ () => {
886
+ }
887
+ );
888
+ }
889
+ try {
890
+ await this.client.connect(this.transport);
891
+ this._isConnected = true;
892
+ } catch (error) {
893
+ if (error instanceof Error && isUnauthorizedError(error)) {
894
+ if (this._pendingAuthFlow) {
895
+ await this._pendingAuthFlow;
896
+ this._pendingAuthFlow = null;
897
+ this.transport = null;
898
+ this.client = null;
899
+ if (authRetryCount >= 1) {
900
+ throw new AuthorizationRequiredError(
901
+ "Authorization completed, but the MCP server still rejected the token. Verify OAuth resource audience and token issuer configuration.",
902
+ { cause: error }
903
+ );
904
+ }
905
+ return this.doConnect(authRetryCount + 1);
906
+ }
907
+ this.transport = null;
908
+ this.client = null;
909
+ throw new AuthorizationRequiredError(
910
+ "Authorization required. Complete the OAuth flow and retry."
911
+ );
912
+ }
913
+ this.transport = null;
914
+ this.client = null;
915
+ if (error instanceof KontextError) throw error;
916
+ throw new KontextError(
917
+ `Failed to connect to MCP server at ${this.mcpEndpointUrl}. ${error instanceof Error ? error.message : String(error)}`,
918
+ "kontext_mcp_connection_failed",
919
+ { cause: error }
920
+ );
921
+ }
922
+ }
923
+ };
924
+
925
+ // src/client/tool-utils.ts
926
+ function parseIntegrationStatus(tools, errors, elicitations) {
927
+ const seen = /* @__PURE__ */ new Set();
928
+ const result = [];
929
+ for (const t of tools) {
930
+ const sid = t.server?.id;
931
+ if (sid && !seen.has(sid)) {
932
+ seen.add(sid);
933
+ result.push({
934
+ id: sid,
935
+ name: t.server?.name ?? sid,
936
+ connected: true
937
+ });
938
+ }
939
+ }
940
+ for (const e of errors) {
941
+ if (!seen.has(e.serverId)) {
942
+ seen.add(e.serverId);
943
+ const elicitation = elicitations?.find(
944
+ (el) => el.integrationId === e.serverId
945
+ );
946
+ result.push({
947
+ id: e.serverId,
948
+ name: e.serverName ?? e.serverId,
949
+ connected: false,
950
+ connectUrl: elicitation?.url
951
+ });
952
+ }
953
+ }
954
+ return result;
955
+ }
956
+
957
+ // src/client/orchestrator/internal/backends.ts
958
+ function gatewayBackendId() {
959
+ return "gateway";
960
+ }
961
+ function internalBackendId(integrationId) {
962
+ return `internal:${integrationId}`;
963
+ }
964
+ function isInternalIntegration(integration) {
965
+ return integration.category === "internal_mcp_credentials";
966
+ }
967
+ function sortInternalIntegrations(integrations) {
968
+ return integrations.filter(isInternalIntegration).sort((a, b) => a.id.localeCompare(b.id));
969
+ }
970
+ function createGatewayBackend(client) {
971
+ return {
972
+ backendId: gatewayBackendId(),
973
+ source: "gateway",
974
+ client
975
+ };
976
+ }
977
+ function createInternalBackend(input) {
978
+ return {
979
+ backendId: internalBackendId(input.integration.id),
980
+ source: "internal",
981
+ client: input.client,
982
+ integrationId: input.integration.id,
983
+ integrationName: input.integration.name
984
+ };
985
+ }
986
+
987
+ // src/client/orchestrator/internal/routes.ts
988
+ function emptyRouteInventorySnapshot() {
989
+ return {
990
+ version: 0,
991
+ tools: [],
992
+ routes: /* @__PURE__ */ new Map(),
993
+ conflicts: []
994
+ };
995
+ }
996
+ function buildRouteInventory(version, candidates, options) {
997
+ const tools = [];
998
+ const routes = /* @__PURE__ */ new Map();
999
+ const conflicts = [];
1000
+ for (const candidate of candidates) {
1001
+ const toolId = candidate.route.toolId;
1002
+ if (!routes.has(toolId)) {
1003
+ routes.set(toolId, candidate.route);
1004
+ tools.push(candidate.tool);
1005
+ continue;
1006
+ }
1007
+ const existing = routes.get(toolId);
1008
+ const decision = options?.onConflict?.(existing, candidate.route) ?? "keep_existing";
1009
+ let kept = existing;
1010
+ let dropped = candidate.route;
1011
+ if (decision === "replace_existing") {
1012
+ const existingIdx = tools.findIndex((tool) => tool.id === toolId);
1013
+ if (existingIdx >= 0) {
1014
+ tools.splice(existingIdx, 1, candidate.tool);
1015
+ } else {
1016
+ tools.push(candidate.tool);
1017
+ }
1018
+ routes.set(toolId, candidate.route);
1019
+ kept = candidate.route;
1020
+ dropped = existing;
1021
+ }
1022
+ conflicts.push({
1023
+ toolId,
1024
+ kept,
1025
+ dropped
1026
+ });
1027
+ }
1028
+ return {
1029
+ version,
1030
+ tools,
1031
+ routes,
1032
+ conflicts
1033
+ };
1034
+ }
1035
+
1036
+ // src/client/orchestrator/internal/inventory.ts
1037
+ var RouteInventoryStore = class {
1038
+ versionCounter = 0;
1039
+ resetGeneration = 0;
1040
+ buildRunCounter = 0;
1041
+ latestCommittedBuildRun = 0;
1042
+ snapshotState = emptyRouteInventorySnapshot();
1043
+ pendingBuilds = /* @__PURE__ */ new Map();
1044
+ get version() {
1045
+ return this.snapshotState.version;
1046
+ }
1047
+ get snapshot() {
1048
+ return this.snapshotState;
1049
+ }
1050
+ routeFor(toolId) {
1051
+ return this.snapshotState.routes.get(toolId);
1052
+ }
1053
+ async build(buildCandidates, options) {
1054
+ const key = options?.key ?? "__default__";
1055
+ const existingBuild = this.pendingBuilds.get(key);
1056
+ if (existingBuild) {
1057
+ return await existingBuild;
1058
+ }
1059
+ const buildGeneration = this.resetGeneration;
1060
+ const buildRun = ++this.buildRunCounter;
1061
+ const pendingPromise = (async () => {
1062
+ const candidates = await buildCandidates();
1063
+ if (this.resetGeneration !== buildGeneration) {
1064
+ return this.snapshotState;
1065
+ }
1066
+ if (buildRun >= this.latestCommittedBuildRun) {
1067
+ this.latestCommittedBuildRun = buildRun;
1068
+ this.versionCounter += 1;
1069
+ const snapshot = buildRouteInventory(this.versionCounter, candidates, {
1070
+ onConflict: options?.onConflict
1071
+ });
1072
+ this.snapshotState = snapshot;
1073
+ return snapshot;
1074
+ }
1075
+ return buildRouteInventory(this.snapshotState.version, candidates, {
1076
+ onConflict: options?.onConflict
1077
+ });
1078
+ })();
1079
+ this.pendingBuilds.set(key, pendingPromise);
1080
+ try {
1081
+ return await pendingPromise;
1082
+ } finally {
1083
+ if (this.pendingBuilds.get(key) === pendingPromise) {
1084
+ this.pendingBuilds.delete(key);
1085
+ }
1086
+ }
1087
+ }
1088
+ reset() {
1089
+ this.resetGeneration += 1;
1090
+ this.versionCounter = 0;
1091
+ this.latestCommittedBuildRun = this.buildRunCounter;
1092
+ this.snapshotState = emptyRouteInventorySnapshot();
1093
+ this.pendingBuilds.clear();
1094
+ }
1095
+ };
1096
+
1097
+ // src/client/orchestrator/internal/policy.ts
1098
+ var defaultRoutingPolicy = {
1099
+ onRouteConflict() {
1100
+ return "keep_existing";
1101
+ }
1102
+ };
1103
+ function toRouteConflictError(input) {
1104
+ return new KontextError(
1105
+ `Route conflict for tool "${input.toolId}". Keeping backend "${input.kept.backendId}" and dropping "${input.dropped.backendId}".`,
1106
+ "kontext_tool_route_conflict",
1107
+ {
1108
+ meta: {
1109
+ toolId: input.toolId,
1110
+ keptBackendId: input.kept.backendId,
1111
+ keptSource: input.kept.source,
1112
+ keptIntegrationId: input.kept.integrationId,
1113
+ droppedBackendId: input.dropped.backendId,
1114
+ droppedSource: input.dropped.source,
1115
+ droppedIntegrationId: input.dropped.integrationId
1116
+ }
1117
+ }
1118
+ );
1119
+ }
1120
+
1121
+ // src/client/orchestrator/internal/state.ts
1122
+ function createOrchestratorStateController(input) {
1123
+ let state = input.initialState ?? "idle";
1124
+ const listeners = /* @__PURE__ */ new Map();
1125
+ function setState(next) {
1126
+ if (state === next) return;
1127
+ state = next;
1128
+ try {
1129
+ input.onStateChange?.(next);
1130
+ } catch {
1131
+ }
1132
+ const handlers = listeners.get("stateChange");
1133
+ if (!handlers) return;
1134
+ for (const handler of handlers) {
1135
+ try {
1136
+ handler(next);
1137
+ } catch {
1138
+ }
1139
+ }
1140
+ }
1141
+ function emitError(error) {
1142
+ const handlers = listeners.get("error");
1143
+ if (!handlers) return;
1144
+ for (const handler of handlers) {
1145
+ try {
1146
+ handler(error);
1147
+ } catch {
1148
+ }
1149
+ }
1150
+ }
1151
+ function on(event, handler) {
1152
+ if (!listeners.has(event)) {
1153
+ listeners.set(event, /* @__PURE__ */ new Set());
1154
+ }
1155
+ listeners.get(event).add(handler);
1156
+ return () => {
1157
+ listeners.get(event)?.delete(handler);
1158
+ };
1159
+ }
1160
+ return {
1161
+ get state() {
1162
+ return state;
1163
+ },
1164
+ setState,
1165
+ emitError,
1166
+ on
1167
+ };
1168
+ }
1169
+
1170
+ // src/client/orchestrator/token-manager.ts
1171
+ function hasFreshStoredToken(tokens, skewMs = 3e4) {
1172
+ if (!tokens?.access_token) return false;
1173
+ const expiresIn = typeof tokens.expires_in === "number" ? tokens.expires_in : Number(tokens.expires_in);
1174
+ const issuedAt = typeof tokens.issued_at === "number" ? tokens.issued_at : Number(tokens.issued_at);
1175
+ if (!Number.isFinite(expiresIn) || !Number.isFinite(issuedAt)) {
1176
+ return false;
1177
+ }
1178
+ const expiresAt = issuedAt + expiresIn * 1e3;
1179
+ return Date.now() + skewMs < expiresAt;
1180
+ }
1181
+ function createTokenManager(input) {
1182
+ const pendingInternalTokenExchange = /* @__PURE__ */ new Map();
1183
+ function tokenStorageKey(sessionKey) {
1184
+ return createStorageKey(input.clientId, sessionKey, StorageKeys.TOKENS);
1185
+ }
1186
+ async function readGatewayTokens() {
1187
+ const identityTokens = await input.storage.getJson(
1188
+ createStorageKey(
1189
+ input.clientId,
1190
+ input.gatewaySessionKey,
1191
+ StorageKeys.IDENTITY_TOKENS
1192
+ )
1193
+ );
1194
+ const gatewayTokens = await input.storage.getJson(tokenStorageKey(input.gatewaySessionKey));
1195
+ return {
1196
+ subjectToken: identityTokens?.access_token ?? gatewayTokens?.access_token ?? null
1197
+ };
1198
+ }
1199
+ async function ensureInternalResourceToken(integration, options) {
1200
+ const internalSessionKey = `${input.baseSessionKey}:internal:${integration.id}`;
1201
+ if (!options?.forceExchange) {
1202
+ const existingToken = await input.storage.getJson(
1203
+ tokenStorageKey(internalSessionKey)
1204
+ );
1205
+ if (hasFreshStoredToken(existingToken)) {
1206
+ return;
1207
+ }
1208
+ }
1209
+ const pending = pendingInternalTokenExchange.get(integration.id);
1210
+ if (pending) {
1211
+ return await pending;
1212
+ }
1213
+ const exchangePromise = (async () => {
1214
+ const { subjectToken: gatewaySubjectToken } = await readGatewayTokens();
1215
+ if (!gatewaySubjectToken) {
1216
+ return;
1217
+ }
1218
+ const body = new URLSearchParams({
1219
+ grant_type: "urn:ietf:params:oauth:grant-type:token-exchange",
1220
+ subject_token_type: "urn:ietf:params:oauth:token-type:access_token",
1221
+ subject_token: gatewaySubjectToken,
1222
+ resource: integration.url,
1223
+ client_id: input.clientId
1224
+ });
1225
+ const response = await fetch(`${input.serverUrl}/oauth2/token`, {
1226
+ method: "POST",
1227
+ headers: {
1228
+ "Content-Type": "application/x-www-form-urlencoded"
1229
+ },
1230
+ body: body.toString()
1231
+ });
1232
+ if (response.status === 401) {
1233
+ throw new AuthorizationRequiredError(
1234
+ "Access token expired or invalid. Re-authenticate and retry."
1235
+ );
1236
+ }
1237
+ if (!response.ok) {
1238
+ throw new KontextError(
1239
+ `Failed to exchange gateway token for internal resource "${integration.id}": HTTP ${response.status}`,
1240
+ "kontext_token_exchange_failed",
1241
+ {
1242
+ statusCode: response.status,
1243
+ meta: {
1244
+ integrationId: integration.id,
1245
+ resource: integration.url
1246
+ }
1247
+ }
1248
+ );
1249
+ }
1250
+ const exchanged = await response.json();
1251
+ if (!exchanged.access_token || !exchanged.token_type) {
1252
+ throw new KontextError(
1253
+ `Token exchange returned an invalid payload for integration "${integration.id}".`,
1254
+ "kontext_token_exchange_failed",
1255
+ {
1256
+ meta: {
1257
+ integrationId: integration.id,
1258
+ resource: integration.url
1259
+ }
1260
+ }
1261
+ );
1262
+ }
1263
+ await input.storage.setJson(tokenStorageKey(internalSessionKey), {
1264
+ ...exchanged,
1265
+ issued_at: Date.now()
1266
+ });
1267
+ })();
1268
+ pendingInternalTokenExchange.set(integration.id, exchangePromise);
1269
+ try {
1270
+ await exchangePromise;
1271
+ } finally {
1272
+ pendingInternalTokenExchange.delete(integration.id);
1273
+ }
1274
+ }
1275
+ return {
1276
+ tokenStorageKey,
1277
+ ensureInternalResourceToken
1278
+ };
1279
+ }
1280
+
1281
+ // src/client/orchestrator/internal-client-registry.ts
1282
+ function createInternalClientRegistry(input) {
1283
+ const internalClients = /* @__PURE__ */ new Map();
1284
+ async function remove(integrationId) {
1285
+ const existing = internalClients.get(integrationId);
1286
+ if (!existing) return;
1287
+ existing.unsubscribeState();
1288
+ existing.unsubscribeError();
1289
+ internalClients.delete(integrationId);
1290
+ input.backends.delete(existing.backendId);
1291
+ try {
1292
+ await existing.client.disconnect();
1293
+ } catch {
1294
+ }
1295
+ }
1296
+ async function sync(discovered) {
1297
+ const sortedInternal = sortInternalIntegrations(discovered);
1298
+ const desiredById = new Map(sortedInternal.map((item) => [item.id, item]));
1299
+ for (const [integrationId, existing] of internalClients) {
1300
+ const next = desiredById.get(integrationId);
1301
+ if (!next) {
1302
+ await remove(integrationId);
1303
+ continue;
1304
+ }
1305
+ if (existing.integration.url !== next.url) {
1306
+ await remove(integrationId);
1307
+ }
1308
+ }
1309
+ for (const integration of sortedInternal) {
1310
+ const existing = internalClients.get(integration.id);
1311
+ if (existing) {
1312
+ existing.integration = integration;
1313
+ const backend = input.backends.get(existing.backendId);
1314
+ if (backend) {
1315
+ backend.integrationName = integration.name;
1316
+ }
1317
+ continue;
1318
+ }
1319
+ const created = input.createClient(integration);
1320
+ input.backends.set(created.backend.backendId, created.backend);
1321
+ internalClients.set(integration.id, {
1322
+ integration,
1323
+ backendId: created.backend.backendId,
1324
+ client: created.client,
1325
+ unsubscribeState: created.unsubscribeState,
1326
+ unsubscribeError: created.unsubscribeError
1327
+ });
1328
+ }
1329
+ }
1330
+ function missingResolved(resolvedIntegrations) {
1331
+ const missing = [];
1332
+ for (const integrationId of internalClients.keys()) {
1333
+ if (!resolvedIntegrations.has(integrationId)) {
1334
+ missing.push(integrationId);
1335
+ }
1336
+ }
1337
+ return missing;
1338
+ }
1339
+ async function dispose(mode) {
1340
+ const entries = [...internalClients.values()];
1341
+ internalClients.clear();
1342
+ for (const backend of [...input.backends.values()]) {
1343
+ if (backend.source === "internal") {
1344
+ input.backends.delete(backend.backendId);
1345
+ }
1346
+ }
1347
+ await Promise.all(
1348
+ entries.map(async (entry) => {
1349
+ entry.unsubscribeState();
1350
+ entry.unsubscribeError();
1351
+ try {
1352
+ if (mode === "signOut") {
1353
+ await entry.client.auth.signOut();
1354
+ } else {
1355
+ await entry.client.disconnect();
1356
+ }
1357
+ } catch {
1358
+ }
1359
+ })
1360
+ );
1361
+ }
1362
+ return {
1363
+ get size() {
1364
+ return internalClients.size;
1365
+ },
1366
+ entries() {
1367
+ return internalClients.entries();
1368
+ },
1369
+ values() {
1370
+ return internalClients.values();
1371
+ },
1372
+ keys() {
1373
+ return internalClients.keys();
1374
+ },
1375
+ get(integrationId) {
1376
+ return internalClients.get(integrationId);
1377
+ },
1378
+ sync,
1379
+ missingResolved,
1380
+ dispose
1381
+ };
1382
+ }
1383
+
1384
+ // src/client/orchestrator/index.ts
1385
+ function isTransientError(err) {
1386
+ if (err instanceof Error && isNetworkError(err)) {
1387
+ return true;
1388
+ }
1389
+ if (isKontextError(err)) {
1390
+ if (err.code === "kontext_network_error") return true;
1391
+ if (err.statusCode === 429) return true;
1392
+ if (typeof err.statusCode === "number" && err.statusCode >= 500) {
1393
+ return true;
1394
+ }
1395
+ return false;
1396
+ }
1397
+ if (typeof err === "object" && err !== null) {
1398
+ const errObj = err;
1399
+ const maybeStatus = errObj.statusCode ?? errObj.status;
1400
+ const status = typeof maybeStatus === "number" ? maybeStatus : void 0;
1401
+ if (status === 429 || typeof status === "number" && status >= 500) {
1402
+ return true;
1403
+ }
1404
+ }
1405
+ return false;
1406
+ }
1407
+ async function withTransientRetry(operation, maxRetries = 1) {
1408
+ const retryDelayMs = 250;
1409
+ for (let attempt = 0; attempt <= maxRetries; attempt += 1) {
1410
+ try {
1411
+ return await operation();
1412
+ } catch (err) {
1413
+ if (attempt >= maxRetries || !isTransientError(err)) {
1414
+ throw err;
1415
+ }
1416
+ await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
1417
+ }
1418
+ }
1419
+ throw new Error("Transient retry loop exhausted unexpectedly.");
1420
+ }
1421
+ function toKontextError(err, context) {
1422
+ const contextMeta = context ? { ...context } : void 0;
1423
+ const mergeMeta = (base) => contextMeta ? { ...base ?? {}, ...contextMeta } : base ?? {};
1424
+ if (isKontextError(err)) {
1425
+ if (!contextMeta) {
1426
+ return err;
1427
+ }
1428
+ const cloned = Object.create(Object.getPrototypeOf(err));
1429
+ Object.defineProperties(cloned, Object.getOwnPropertyDescriptors(err));
1430
+ Object.defineProperty(cloned, "meta", {
1431
+ value: mergeMeta(err.meta),
1432
+ enumerable: true,
1433
+ writable: true,
1434
+ configurable: true
1435
+ });
1436
+ return cloned;
1437
+ }
1438
+ if (err instanceof Error) {
1439
+ if (isUnauthorizedError(err)) {
1440
+ return new AuthorizationRequiredError(err.message, {
1441
+ meta: mergeMeta(),
1442
+ cause: err
1443
+ });
1444
+ }
1445
+ return new KontextError(err.message, "kontext_unknown_error", {
1446
+ meta: mergeMeta(),
1447
+ cause: err
1448
+ });
1449
+ }
1450
+ return new KontextError(String(err), "kontext_unknown_error", {
1451
+ meta: mergeMeta()
1452
+ });
1453
+ }
1454
+ function isAuthorizationRequired(err) {
1455
+ if (err instanceof AuthorizationRequiredError) return true;
1456
+ if (isKontextError(err)) {
1457
+ return err.code === "kontext_authorization_required";
1458
+ }
1459
+ if (typeof err === "object" && err !== null) {
1460
+ return err.code === "kontext_authorization_required";
1461
+ }
1462
+ return false;
1463
+ }
1464
+ function isTokenExchangeFailure(err) {
1465
+ if (isKontextError(err)) {
1466
+ return err.code === "kontext_token_exchange_failed";
1467
+ }
1468
+ if (typeof err === "object" && err !== null) {
1469
+ return err.code === "kontext_token_exchange_failed";
1470
+ }
1471
+ return false;
1472
+ }
1473
+ function isAuthRecoveryRequired(err) {
1474
+ return isAuthorizationRequired(err) || isTokenExchangeFailure(err);
1475
+ }
1476
+ function createKontextOrchestrator(config) {
1477
+ if (!config.clientId) {
1478
+ throw new ConfigError(
1479
+ "clientId is required. Pass it in KontextOrchestratorConfig.",
1480
+ "kontext_config_missing_client_id"
1481
+ );
1482
+ }
1483
+ if (!config.redirectUri) {
1484
+ throw new ConfigError(
1485
+ "redirectUri is required. Set it to the URL where OAuth should redirect after authorization.",
1486
+ "kontext_config_missing_redirect_uri"
1487
+ );
1488
+ }
1489
+ if (!config.onAuthRequired) {
1490
+ throw new ConfigError(
1491
+ "onAuthRequired callback is required. Provide a function that opens the OAuth URL.",
1492
+ "kontext_config_missing_auth_handler"
1493
+ );
1494
+ }
1495
+ const baseSessionKey = config.sessionKey ?? "default";
1496
+ const serverUrl = normalizeKontextServerUrl(
1497
+ config.serverUrl ?? "https://api.kontext.dev"
1498
+ );
1499
+ const sharedStorage = config.storage ?? new MemoryStorage();
1500
+ const gatewaySessionKey = `${baseSessionKey}:gateway`;
1501
+ const authSourceQueue = [];
1502
+ const stateController = createOrchestratorStateController({
1503
+ initialState: "idle",
1504
+ onStateChange: config.onStateChange
1505
+ });
1506
+ const routeInventory = new RouteInventoryStore();
1507
+ const routingPolicy = defaultRoutingPolicy;
1508
+ const runtimeIntegrations = /* @__PURE__ */ new Map();
1509
+ const backends = /* @__PURE__ */ new Map();
1510
+ const managedInternalOps = /* @__PURE__ */ new Map();
1511
+ const resolvedInternalListings = /* @__PURE__ */ new Set();
1512
+ const tokenManager = createTokenManager({
1513
+ clientId: config.clientId,
1514
+ baseSessionKey,
1515
+ gatewaySessionKey,
1516
+ serverUrl,
1517
+ storage: sharedStorage
1518
+ });
1519
+ let pendingIntegrationRefresh = null;
1520
+ const gatewayClient = createSingleEndpointKontextClient({
1521
+ clientId: config.clientId,
1522
+ redirectUri: config.redirectUri,
1523
+ serverUrl: config.serverUrl,
1524
+ storage: sharedStorage,
1525
+ sessionKey: gatewaySessionKey,
1526
+ onAuthRequired: async (url) => {
1527
+ authSourceQueue.push("gateway");
1528
+ return await config.onAuthRequired(url);
1529
+ },
1530
+ onIntegrationRequired: config.onIntegrationRequired
1531
+ });
1532
+ const gatewayBackend = createGatewayBackend(gatewayClient);
1533
+ backends.set(gatewayBackendId(), gatewayBackend);
1534
+ gatewayClient.on("stateChange", (state) => {
1535
+ if (state === "needs_auth") {
1536
+ stateController.setState("needs_auth");
1537
+ }
1538
+ });
1539
+ gatewayClient.on("error", (error) => {
1540
+ const translated = toKontextError(error, {
1541
+ backendId: gatewayBackendId(),
1542
+ source: "gateway",
1543
+ operation: "client_error_event"
1544
+ });
1545
+ stateController.emitError(translated);
1546
+ if (isAuthRecoveryRequired(translated)) {
1547
+ stateController.setState("needs_auth");
1548
+ }
1549
+ });
1550
+ const ensureInternalResourceToken = tokenManager.ensureInternalResourceToken;
1551
+ function isInternalOpManaged(integrationId) {
1552
+ return (managedInternalOps.get(integrationId) ?? 0) > 0;
1553
+ }
1554
+ async function runManagedInternalOp(integrationId, operation) {
1555
+ managedInternalOps.set(
1556
+ integrationId,
1557
+ (managedInternalOps.get(integrationId) ?? 0) + 1
1558
+ );
1559
+ try {
1560
+ return await operation();
1561
+ } finally {
1562
+ const next = (managedInternalOps.get(integrationId) ?? 1) - 1;
1563
+ if (next <= 0) {
1564
+ managedInternalOps.delete(integrationId);
1565
+ } else {
1566
+ managedInternalOps.set(integrationId, next);
1567
+ }
1568
+ }
1569
+ }
1570
+ function createInternalClient(integration) {
1571
+ const client = createSingleEndpointKontextClient({
1572
+ clientId: config.clientId,
1573
+ redirectUri: config.redirectUri,
1574
+ url: integration.url,
1575
+ serverUrl: config.serverUrl,
1576
+ storage: sharedStorage,
1577
+ sessionKey: `${baseSessionKey}:internal:${integration.id}`,
1578
+ onAuthRequired: async (url) => {
1579
+ authSourceQueue.push(integration.id);
1580
+ return await config.onAuthRequired(url);
1581
+ },
1582
+ onIntegrationRequired: config.onIntegrationRequired
1583
+ });
1584
+ const unsubscribeState = client.on("stateChange", (state) => {
1585
+ if (state === "needs_auth") {
1586
+ stateController.setState("needs_auth");
1587
+ }
1588
+ });
1589
+ const unsubscribeError = client.on("error", (error) => {
1590
+ const translated = toKontextError(error, {
1591
+ backendId: internalBackendId(integration.id),
1592
+ source: "internal",
1593
+ integrationId: integration.id,
1594
+ operation: "client_error_event"
1595
+ });
1596
+ if (isInternalOpManaged(integration.id) && isAuthorizationRequired(translated)) {
1597
+ return;
1598
+ }
1599
+ if (isAuthRecoveryRequired(translated)) {
1600
+ stateController.setState("needs_auth");
1601
+ return;
1602
+ }
1603
+ stateController.emitError(translated);
1604
+ });
1605
+ const backend = createInternalBackend({ integration, client });
1606
+ return { backend, client, unsubscribeState, unsubscribeError };
1607
+ }
1608
+ const internalClientRegistry = createInternalClientRegistry({
1609
+ backends,
1610
+ createClient: createInternalClient
1611
+ });
1612
+ async function refreshIntegrationInventory(force = false) {
1613
+ if (pendingIntegrationRefresh) {
1614
+ if (!force) {
1615
+ return await pendingIntegrationRefresh;
1616
+ }
1617
+ await pendingIntegrationRefresh;
1618
+ }
1619
+ const refreshPromise = (async () => {
1620
+ const items = await withTransientRetry(
1621
+ async () => await gatewayClient.mcp.listRuntimeIntegrations()
1622
+ );
1623
+ await applyRuntimeIntegrations(items);
1624
+ return items;
1625
+ })();
1626
+ pendingIntegrationRefresh = refreshPromise;
1627
+ try {
1628
+ return await refreshPromise;
1629
+ } finally {
1630
+ if (pendingIntegrationRefresh === refreshPromise) {
1631
+ pendingIntegrationRefresh = null;
1632
+ }
1633
+ }
1634
+ }
1635
+ async function applyRuntimeIntegrations(integrations) {
1636
+ runtimeIntegrations.clear();
1637
+ for (const item of integrations) {
1638
+ runtimeIntegrations.set(item.id, item);
1639
+ }
1640
+ await internalClientRegistry.sync(integrations);
1641
+ }
1642
+ async function buildInventoryCandidates(options) {
1643
+ const candidates = [];
1644
+ resolvedInternalListings.clear();
1645
+ const pendingInternalAuthRetries = /* @__PURE__ */ new Set();
1646
+ const gatewayTools = await gatewayClient.tools.list(options);
1647
+ for (const tool of gatewayTools) {
1648
+ candidates.push({
1649
+ tool,
1650
+ route: {
1651
+ toolId: tool.id,
1652
+ backendId: gatewayBackendId(),
1653
+ source: "gateway",
1654
+ backendToolId: tool.id
1655
+ }
1656
+ });
1657
+ }
1658
+ if (options?.runtimeIntegrations) {
1659
+ await applyRuntimeIntegrations(options.runtimeIntegrations);
1660
+ } else {
1661
+ await refreshIntegrationInventory();
1662
+ }
1663
+ const sortedInternalEntries = [...internalClientRegistry.values()].sort(
1664
+ (a, b) => a.integration.id.localeCompare(b.integration.id)
1665
+ );
1666
+ const addInternalToolsForEntry = async (entry) => {
1667
+ const internalTools = await withTransientRetry(
1668
+ async () => await runManagedInternalOp(
1669
+ entry.integration.id,
1670
+ () => entry.client.tools.list()
1671
+ )
1672
+ );
1673
+ resolvedInternalListings.add(entry.integration.id);
1674
+ for (const tool of internalTools) {
1675
+ const backendToolId = tool.id || tool.name;
1676
+ const unifiedId = `${entry.integration.id}:${tool.name}`;
1677
+ candidates.push({
1678
+ tool: {
1679
+ id: unifiedId,
1680
+ name: tool.name,
1681
+ description: tool.description,
1682
+ inputSchema: tool.inputSchema,
1683
+ server: {
1684
+ id: entry.integration.id,
1685
+ name: entry.integration.name
1686
+ }
1687
+ },
1688
+ route: {
1689
+ toolId: unifiedId,
1690
+ backendId: entry.backendId,
1691
+ source: "internal",
1692
+ backendToolId,
1693
+ integrationId: entry.integration.id
1694
+ }
1695
+ });
1696
+ }
1697
+ };
1698
+ for (const entry of sortedInternalEntries) {
1699
+ try {
1700
+ await ensureInternalResourceToken(entry.integration);
1701
+ await addInternalToolsForEntry(entry);
1702
+ } catch (err) {
1703
+ const translated = toKontextError(err, {
1704
+ backendId: entry.backendId,
1705
+ source: "internal",
1706
+ integrationId: entry.integration.id,
1707
+ operation: "tools.list"
1708
+ });
1709
+ if (isAuthorizationRequired(translated)) {
1710
+ pendingInternalAuthRetries.add(entry.integration.id);
1711
+ continue;
1712
+ }
1713
+ if (isTokenExchangeFailure(translated)) {
1714
+ stateController.setState("needs_auth");
1715
+ }
1716
+ stateController.emitError(translated);
1717
+ }
1718
+ }
1719
+ if (pendingInternalAuthRetries.size > 0) {
1720
+ let hasUnresolvedAuth = false;
1721
+ for (const integrationId of pendingInternalAuthRetries) {
1722
+ const entry = internalClientRegistry.get(integrationId);
1723
+ if (!entry) continue;
1724
+ try {
1725
+ await ensureInternalResourceToken(entry.integration, {
1726
+ forceExchange: true
1727
+ });
1728
+ await runManagedInternalOp(integrationId, async () => {
1729
+ await entry.client.disconnect();
1730
+ await entry.client.connect();
1731
+ });
1732
+ await addInternalToolsForEntry(entry);
1733
+ } catch (err) {
1734
+ const translated = toKontextError(err);
1735
+ if (isAuthRecoveryRequired(translated)) {
1736
+ hasUnresolvedAuth = true;
1737
+ if (isTokenExchangeFailure(translated)) {
1738
+ stateController.emitError(translated);
1739
+ }
1740
+ continue;
1741
+ }
1742
+ stateController.emitError(translated);
1743
+ }
1744
+ }
1745
+ if (hasUnresolvedAuth) {
1746
+ stateController.setState("needs_auth");
1747
+ } else if (stateController.state === "needs_auth" && gatewayClient.state === "ready") {
1748
+ stateController.setState("ready");
1749
+ }
1750
+ }
1751
+ return candidates;
1752
+ }
1753
+ async function buildToolInventory(options) {
1754
+ const inventoryKey = JSON.stringify({
1755
+ limit: options?.limit ?? null,
1756
+ runtimeIntegrations: options?.runtimeIntegrations?.map((integration) => integration.id).sort() ?? null
1757
+ });
1758
+ const snapshot = await routeInventory.build(
1759
+ async () => await buildInventoryCandidates(options),
1760
+ {
1761
+ key: inventoryKey,
1762
+ onConflict: (existing, incoming) => routingPolicy.onRouteConflict({
1763
+ toolId: existing.toolId,
1764
+ existing,
1765
+ incoming
1766
+ })
1767
+ }
1768
+ );
1769
+ return {
1770
+ tools: snapshot.tools,
1771
+ conflicts: snapshot.conflicts
1772
+ };
1773
+ }
1774
+ function emitRouteConflicts(conflicts) {
1775
+ for (const conflict of conflicts) {
1776
+ stateController.emitError(
1777
+ toRouteConflictError({
1778
+ toolId: conflict.toolId,
1779
+ kept: conflict.kept,
1780
+ dropped: conflict.dropped
1781
+ })
1782
+ );
1783
+ }
1784
+ }
1785
+ function getInternalIntegrationsMissingTools() {
1786
+ return internalClientRegistry.missingResolved(resolvedInternalListings);
1787
+ }
1788
+ async function disposeInternalClients(mode) {
1789
+ await internalClientRegistry.dispose(mode);
1790
+ }
1791
+ async function ensureConnected() {
1792
+ if (stateController.state === "ready") return;
1793
+ if (stateController.state === "needs_auth" && gatewayClient.state === "ready") {
1794
+ return;
1795
+ }
1796
+ stateController.setState("connecting");
1797
+ try {
1798
+ await gatewayClient.connect();
1799
+ await refreshIntegrationInventory(true);
1800
+ stateController.setState("ready");
1801
+ } catch (err) {
1802
+ const translated = toKontextError(err, {
1803
+ backendId: gatewayBackendId(),
1804
+ source: "gateway",
1805
+ operation: "connect"
1806
+ });
1807
+ if (isAuthRecoveryRequired(translated)) {
1808
+ stateController.setState("needs_auth");
1809
+ } else {
1810
+ stateController.setState("failed");
1811
+ }
1812
+ stateController.emitError(translated);
1813
+ throw translated;
1814
+ }
1815
+ }
1816
+ async function routeForExecution(toolId) {
1817
+ let route = routeInventory.routeFor(toolId);
1818
+ if (route) return route;
1819
+ const inventory = await buildToolInventory();
1820
+ emitRouteConflicts(inventory.conflicts);
1821
+ route = routeInventory.routeFor(toolId);
1822
+ if (route) return route;
1823
+ throw new KontextError(
1824
+ `Unknown tool "${toolId}". Call tools.list() to refresh available tools.`,
1825
+ "kontext_tool_not_found",
1826
+ { meta: { toolId } }
1827
+ );
1828
+ }
1829
+ const orchestrator = {
1830
+ get state() {
1831
+ return stateController.state;
1832
+ },
1833
+ async connect() {
1834
+ await ensureConnected();
1835
+ },
1836
+ async disconnect() {
1837
+ await disposeInternalClients("disconnect");
1838
+ runtimeIntegrations.clear();
1839
+ routeInventory.reset();
1840
+ authSourceQueue.length = 0;
1841
+ await gatewayClient.disconnect();
1842
+ stateController.setState("idle");
1843
+ },
1844
+ async getConnectPageUrl() {
1845
+ await ensureConnected();
1846
+ return await gatewayClient.getConnectPageUrl();
1847
+ },
1848
+ auth: {
1849
+ async signIn() {
1850
+ if (stateController.state === "needs_auth" && gatewayClient.state === "ready") {
1851
+ await refreshIntegrationInventory(true);
1852
+ let unresolvedInternalAuth = false;
1853
+ for (const [
1854
+ integrationId,
1855
+ entry
1856
+ ] of internalClientRegistry.entries()) {
1857
+ try {
1858
+ await runManagedInternalOp(
1859
+ integrationId,
1860
+ () => entry.client.auth.signIn()
1861
+ );
1862
+ } catch (err) {
1863
+ const translated = toKontextError(err);
1864
+ if (isAuthorizationRequired(translated)) {
1865
+ unresolvedInternalAuth = true;
1866
+ continue;
1867
+ }
1868
+ stateController.emitError(translated);
1869
+ }
1870
+ }
1871
+ const inventory = await buildToolInventory();
1872
+ emitRouteConflicts(inventory.conflicts);
1873
+ const missingInternal = getInternalIntegrationsMissingTools();
1874
+ if (!unresolvedInternalAuth && missingInternal.length === 0) {
1875
+ stateController.setState("ready");
1876
+ }
1877
+ return;
1878
+ }
1879
+ await ensureConnected();
1880
+ },
1881
+ async signOut() {
1882
+ await disposeInternalClients("signOut");
1883
+ runtimeIntegrations.clear();
1884
+ routeInventory.reset();
1885
+ authSourceQueue.length = 0;
1886
+ await gatewayClient.auth.signOut();
1887
+ stateController.setState("idle");
1888
+ },
1889
+ async handleCallback(url) {
1890
+ if (internalClientRegistry.size === 0) {
1891
+ try {
1892
+ await refreshIntegrationInventory(true);
1893
+ } catch (err) {
1894
+ stateController.emitError(
1895
+ toKontextError(err, {
1896
+ backendId: gatewayBackendId(),
1897
+ source: "gateway",
1898
+ operation: "auth.handleCallback.preload"
1899
+ })
1900
+ );
1901
+ }
1902
+ }
1903
+ const ordered = [];
1904
+ for (const sourceId of authSourceQueue) {
1905
+ if (sourceId === "gateway") {
1906
+ ordered.push({ client: gatewayClient, sourceId });
1907
+ continue;
1908
+ }
1909
+ const active = internalClientRegistry.get(sourceId);
1910
+ if (active) {
1911
+ ordered.push({ client: active.client, sourceId });
1912
+ }
1913
+ }
1914
+ if (gatewayClient.auth.isCallback(url)) {
1915
+ ordered.push({ client: gatewayClient });
1916
+ }
1917
+ for (const entry of internalClientRegistry.values()) {
1918
+ if (entry.client.auth.isCallback(url)) {
1919
+ ordered.push({ client: entry.client });
1920
+ }
1921
+ }
1922
+ ordered.push({ client: gatewayClient });
1923
+ ordered.push(
1924
+ ...[...internalClientRegistry.values()].sort((a, b) => a.integration.id.localeCompare(b.integration.id)).map((entry) => ({ client: entry.client }))
1925
+ );
1926
+ const unique = [];
1927
+ const seen = /* @__PURE__ */ new Set();
1928
+ for (const entry of ordered) {
1929
+ if (seen.has(entry.client)) continue;
1930
+ seen.add(entry.client);
1931
+ unique.push(entry);
1932
+ }
1933
+ let handledBy;
1934
+ let lastError = void 0;
1935
+ for (const entry of unique) {
1936
+ try {
1937
+ await entry.client.auth.handleCallback(url);
1938
+ handledBy = entry;
1939
+ break;
1940
+ } catch (err) {
1941
+ lastError = err;
1942
+ }
1943
+ }
1944
+ if (handledBy) {
1945
+ for (let idx = authSourceQueue.length - 1; idx >= 0; idx -= 1) {
1946
+ const sourceId = authSourceQueue[idx];
1947
+ const sourceClient = sourceId === "gateway" ? gatewayClient : internalClientRegistry.get(sourceId)?.client;
1948
+ if (sourceClient === handledBy.client) {
1949
+ authSourceQueue.splice(idx, 1);
1950
+ }
1951
+ }
1952
+ }
1953
+ if (!handledBy && lastError) {
1954
+ throw toKontextError(lastError, {
1955
+ backendId: gatewayBackendId(),
1956
+ source: "gateway",
1957
+ operation: "auth.handleCallback"
1958
+ });
1959
+ }
1960
+ try {
1961
+ await ensureConnected();
1962
+ } catch (err) {
1963
+ stateController.emitError(
1964
+ toKontextError(err, {
1965
+ backendId: gatewayBackendId(),
1966
+ source: "gateway",
1967
+ operation: "post_callback_connect"
1968
+ })
1969
+ );
1970
+ }
1971
+ },
1972
+ isCallback(url) {
1973
+ if (gatewayClient.auth.isCallback(url)) return true;
1974
+ for (const entry of internalClientRegistry.values()) {
1975
+ if (entry.client.auth.isCallback(url)) return true;
1976
+ }
1977
+ return false;
1978
+ },
1979
+ get isAuthenticated() {
1980
+ return stateController.state === "ready" || gatewayClient.auth.isAuthenticated;
1981
+ }
1982
+ },
1983
+ integrations: {
1984
+ async list() {
1985
+ await ensureConnected();
1986
+ const discovered = await refreshIntegrationInventory(true);
1987
+ let gatewayStatuses = [];
1988
+ try {
1989
+ gatewayStatuses = await gatewayClient.integrations.list();
1990
+ } catch (err) {
1991
+ stateController.emitError(
1992
+ toKontextError(err, {
1993
+ backendId: gatewayBackendId(),
1994
+ source: "gateway",
1995
+ operation: "integrations.list"
1996
+ })
1997
+ );
1998
+ }
1999
+ const gatewayById = new Map(gatewayStatuses.map((i) => [i.id, i]));
2000
+ const needsInternalConnectLink = discovered.some(
2001
+ (i) => i.category === "internal_mcp_credentials" && !i.connection?.connected
2002
+ );
2003
+ let sharedConnectUrl;
2004
+ if (needsInternalConnectLink) {
2005
+ try {
2006
+ sharedConnectUrl = (await gatewayClient.getConnectPageUrl()).connectUrl;
2007
+ } catch {
2008
+ sharedConnectUrl = void 0;
2009
+ }
2010
+ }
2011
+ return discovered.map((integration) => {
2012
+ const gatewayStatus = gatewayById.get(integration.id);
2013
+ const connected = gatewayStatus?.connected ?? integration.connection?.connected ?? false;
2014
+ const connectUrl = gatewayStatus?.connectUrl ?? (!connected && integration.category === "internal_mcp_credentials" ? sharedConnectUrl : void 0);
2015
+ const reason = gatewayStatus?.reason ?? (!connected && integration.category === "internal_mcp_credentials" ? "credentials_required" : void 0);
2016
+ return {
2017
+ id: integration.id,
2018
+ name: integration.name,
2019
+ connected,
2020
+ connectUrl,
2021
+ reason
2022
+ };
2023
+ });
2024
+ }
2025
+ },
2026
+ tools: {
2027
+ async list(options) {
2028
+ await ensureConnected();
2029
+ let inventory = await buildToolInventory(options);
2030
+ const missingInternal = getInternalIntegrationsMissingTools();
2031
+ if (missingInternal.length > 0) {
2032
+ const refreshed = await refreshIntegrationInventory(true);
2033
+ inventory = await buildToolInventory({
2034
+ ...options,
2035
+ runtimeIntegrations: refreshed
2036
+ });
2037
+ }
2038
+ emitRouteConflicts(inventory.conflicts);
2039
+ const unresolvedInternal = getInternalIntegrationsMissingTools();
2040
+ if (stateController.state === "needs_auth" && gatewayClient.state === "ready" && unresolvedInternal.length === 0) {
2041
+ stateController.setState("ready");
2042
+ }
2043
+ return inventory.tools;
2044
+ },
2045
+ async execute(toolId, args) {
2046
+ await ensureConnected();
2047
+ const route = await routeForExecution(toolId);
2048
+ try {
2049
+ if (route.source === "gateway") {
2050
+ return await gatewayClient.tools.execute(route.backendToolId, args);
2051
+ }
2052
+ const integrationId = route.integrationId;
2053
+ if (!integrationId) {
2054
+ throw new KontextError(
2055
+ `Route for tool "${toolId}" is missing integration metadata.`,
2056
+ "kontext_tool_not_found",
2057
+ { meta: { toolId, route } }
2058
+ );
2059
+ }
2060
+ let entry = internalClientRegistry.get(integrationId);
2061
+ if (!entry) {
2062
+ await refreshIntegrationInventory(true);
2063
+ entry = internalClientRegistry.get(integrationId);
2064
+ }
2065
+ if (!entry) {
2066
+ throw new KontextError(
2067
+ `Internal integration "${integrationId}" is no longer attached.`,
2068
+ "kontext_tool_not_found",
2069
+ { meta: { integrationId } }
2070
+ );
2071
+ }
2072
+ await ensureInternalResourceToken(entry.integration);
2073
+ try {
2074
+ const executeInternal = async () => await withTransientRetry(
2075
+ async () => await runManagedInternalOp(
2076
+ integrationId,
2077
+ () => entry.client.tools.execute(route.backendToolId, args)
2078
+ )
2079
+ );
2080
+ return await executeInternal();
2081
+ } catch (innerErr) {
2082
+ const innerTranslated = toKontextError(innerErr, {
2083
+ backendId: route.backendId,
2084
+ source: route.source,
2085
+ integrationId: route.integrationId,
2086
+ operation: "tools.execute",
2087
+ toolId
2088
+ });
2089
+ throw innerTranslated;
2090
+ }
2091
+ } catch (err) {
2092
+ const translated = toKontextError(err, {
2093
+ backendId: route.backendId,
2094
+ source: route.source,
2095
+ integrationId: route.integrationId,
2096
+ operation: "tools.execute",
2097
+ toolId
2098
+ });
2099
+ if (isAuthRecoveryRequired(translated)) {
2100
+ stateController.setState("needs_auth");
2101
+ }
2102
+ stateController.emitError(translated);
2103
+ throw translated;
2104
+ }
2105
+ }
2106
+ },
2107
+ on(event, handler) {
2108
+ if (event === "stateChange") {
2109
+ return stateController.on("stateChange", handler);
2110
+ }
2111
+ return stateController.on("error", handler);
2112
+ },
2113
+ get mcp() {
2114
+ return gatewayClient.mcp;
2115
+ }
2116
+ };
2117
+ return orchestrator;
2118
+ }
2119
+
2120
+ // src/client/index.ts
2121
+ var META_TOOL_NAMES = /* @__PURE__ */ new Set(["SEARCH_TOOLS", "EXECUTE_TOOL"]);
2122
+ function hasMetaTools(tools) {
2123
+ let hasSearch = false;
2124
+ let hasExecute = false;
2125
+ for (const tool of tools) {
2126
+ if (tool.name === "SEARCH_TOOLS") hasSearch = true;
2127
+ if (tool.name === "EXECUTE_TOOL") hasExecute = true;
2128
+ }
2129
+ return hasSearch && hasExecute;
2130
+ }
2131
+ function extractJsonResourceText(result) {
2132
+ if (!result || typeof result !== "object") return null;
2133
+ const content = result.content;
2134
+ if (!Array.isArray(content)) return null;
2135
+ for (const item of content) {
2136
+ if (item.type === "resource" && item.resource?.mimeType === "application/json" && item.resource.text) {
2137
+ return item.resource.text;
2138
+ }
2139
+ }
2140
+ return null;
2141
+ }
2142
+ function extractTextContent(result) {
2143
+ if (!result || typeof result !== "object") return String(result ?? "");
2144
+ const r = result;
2145
+ if (r.content && Array.isArray(r.content)) {
2146
+ const texts = r.content.filter((c) => c.type === "text" && c.text).map((c) => c.text);
2147
+ if (texts.length > 0) return texts.join("\n");
2148
+ const resourceTexts = r.content.filter((c) => c.type === "resource" && c.resource?.text).map((c) => c.resource.text);
2149
+ if (resourceTexts.length > 0) {
2150
+ return resourceTexts.map((text) => {
2151
+ try {
2152
+ return extractTextContent(JSON.parse(text));
2153
+ } catch {
2154
+ return text;
2155
+ }
2156
+ }).join("\n");
2157
+ }
2158
+ return JSON.stringify(r.content);
2159
+ }
2160
+ return JSON.stringify(result);
2161
+ }
2162
+ function translateError(err) {
2163
+ if (isKontextError(err)) return err;
2164
+ if (!(err instanceof Error)) {
2165
+ return new KontextError(String(err), "kontext_unknown_error");
2166
+ }
2167
+ const props = err;
2168
+ if (props.code === -32042) {
2169
+ const elicitations = props.elicitations ?? props.data?.elicitations;
2170
+ const elicitation = elicitations?.[0];
2171
+ return new IntegrationConnectionRequiredError(
2172
+ elicitation?.integrationId ?? "unknown",
2173
+ {
2174
+ integrationName: elicitation?.integrationName,
2175
+ connectUrl: elicitation?.url,
2176
+ message: elicitation?.message,
2177
+ cause: err
2178
+ }
2179
+ );
2180
+ }
2181
+ const statusCode = props.statusCode ?? props.status;
2182
+ if (typeof statusCode === "number" && statusCode >= 400) {
2183
+ if (statusCode === 401) {
2184
+ return new AuthorizationRequiredError(err.message, { cause: err });
2185
+ }
2186
+ return new KontextError(err.message, "kontext_server_error", {
2187
+ statusCode,
2188
+ cause: err
2189
+ });
2190
+ }
2191
+ if (isUnauthorizedError(err)) {
2192
+ return new AuthorizationRequiredError(err.message, { cause: err });
2193
+ }
2194
+ if (isNetworkError(err)) {
2195
+ return new NetworkError(err.message, { cause: err });
2196
+ }
2197
+ return new KontextError(err.message, "kontext_unknown_error", {
2198
+ cause: err
2199
+ });
2200
+ }
2201
+ function createSingleEndpointKontextClient(config) {
2202
+ if (!config.clientId) {
2203
+ throw new ConfigError(
2204
+ "clientId is required. Pass it in KontextClientConfig or set KONTEXT_CLIENT_ID.",
2205
+ "kontext_config_missing_client_id"
2206
+ );
2207
+ }
2208
+ if (!config.redirectUri) {
2209
+ throw new ConfigError(
2210
+ "redirectUri is required. Set it to the URL where OAuth should redirect after authorization.",
2211
+ "kontext_config_missing_redirect_uri"
2212
+ );
2213
+ }
2214
+ if (!config.onAuthRequired) {
2215
+ throw new ConfigError(
2216
+ "onAuthRequired callback is required. Provide a function that opens the OAuth URL.",
2217
+ "kontext_config_missing_auth_handler"
2218
+ );
2219
+ }
2220
+ let _state = "idle";
2221
+ const _listeners = /* @__PURE__ */ new Map();
2222
+ let _metaToolMode = null;
2223
+ const mcp = new KontextMcp({
2224
+ clientId: config.clientId,
2225
+ url: config.url,
2226
+ server: config.serverUrl,
2227
+ redirectUri: config.redirectUri,
2228
+ storage: config.storage,
2229
+ sessionKey: config.sessionKey,
2230
+ onAuthRequired: config.onAuthRequired,
2231
+ // Route MCP elicitation to the high-level callback.
2232
+ // KontextMcp calls this then re-throws; client.tools.execute() catches
2233
+ // the re-thrown error and handles translation.
2234
+ onElicitationUrl: config.onIntegrationRequired ? (entry) => {
2235
+ config.onIntegrationRequired(entry.url, {
2236
+ id: entry.integrationId ?? "unknown",
2237
+ name: entry.integrationName ?? entry.message
2238
+ });
2239
+ } : void 0
2240
+ });
2241
+ function setState(newState) {
2242
+ if (_state === newState) return;
2243
+ _state = newState;
2244
+ try {
2245
+ config.onStateChange?.(newState);
2246
+ } catch {
2247
+ }
2248
+ const handlers = _listeners.get("stateChange");
2249
+ if (handlers) {
2250
+ for (const handler of handlers) {
2251
+ try {
2252
+ handler(newState);
2253
+ } catch {
2254
+ }
2255
+ }
2256
+ }
2257
+ }
2258
+ function emitError(error) {
2259
+ const handlers = _listeners.get("error");
2260
+ if (handlers) {
2261
+ for (const handler of handlers) {
2262
+ try {
2263
+ handler(error);
2264
+ } catch {
2265
+ }
2266
+ }
2267
+ }
2268
+ }
2269
+ async function fetchGatewayTools(limit = 100) {
2270
+ const result = await mcp.callTool("SEARCH_TOOLS", { limit });
2271
+ const jsonText = extractJsonResourceText(result);
2272
+ if (!jsonText) {
2273
+ throw new KontextError(
2274
+ "SEARCH_TOOLS did not return JSON resource content. The server may not support the gateway protocol.",
2275
+ "kontext_tool_response_empty"
2276
+ );
2277
+ }
2278
+ let parsed;
2279
+ try {
2280
+ parsed = JSON.parse(jsonText);
2281
+ } catch (e) {
2282
+ throw new KontextError(
2283
+ `SEARCH_TOOLS returned invalid JSON: ${e instanceof Error ? e.message : String(e)}`,
2284
+ "kontext_tool_response_invalid_json"
2285
+ );
2286
+ }
2287
+ if (Array.isArray(parsed)) {
2288
+ return { tools: parsed, errors: [] };
2289
+ }
2290
+ if (parsed && typeof parsed === "object") {
2291
+ const obj = parsed;
2292
+ return {
2293
+ tools: Array.isArray(obj.items) ? obj.items : [],
2294
+ errors: Array.isArray(obj.errors) ? obj.errors : [],
2295
+ elicitations: Array.isArray(obj.elicitations) ? obj.elicitations : void 0
2296
+ };
2297
+ }
2298
+ throw new KontextError(
2299
+ "SEARCH_TOOLS response was not a JSON array or object. Check the server version.",
2300
+ "kontext_tool_response_unexpected"
2301
+ );
2302
+ }
2303
+ function toKontextTool(tool) {
2304
+ return {
2305
+ id: tool.id,
2306
+ name: tool.name,
2307
+ description: tool.description,
2308
+ inputSchema: tool.inputSchema,
2309
+ server: tool.server ? { id: tool.server.id ?? "", name: tool.server.name } : void 0
2310
+ };
2311
+ }
2312
+ async function ensureConnected() {
2313
+ if (_state === "ready" && mcp.isConnected) return;
2314
+ setState("connecting");
2315
+ try {
2316
+ const mcpTools = await mcp.listTools();
2317
+ _metaToolMode = hasMetaTools(mcpTools);
2318
+ setState("ready");
2319
+ } catch (err) {
2320
+ const translated = translateError(err);
2321
+ if (translated instanceof AuthorizationRequiredError) {
2322
+ setState("needs_auth");
2323
+ } else {
2324
+ setState("failed");
2325
+ }
2326
+ emitError(translated);
2327
+ throw translated;
2328
+ }
2329
+ }
2330
+ const client = {
2331
+ get state() {
2332
+ return _state;
2333
+ },
2334
+ async connect() {
2335
+ await ensureConnected();
2336
+ },
2337
+ async disconnect() {
2338
+ await mcp.disconnect();
2339
+ _metaToolMode = null;
2340
+ setState("idle");
2341
+ },
2342
+ async getConnectPageUrl() {
2343
+ await ensureConnected();
2344
+ try {
2345
+ return await mcp.createConnectSession();
2346
+ } catch (err) {
2347
+ const translated = translateError(err);
2348
+ if (translated instanceof AuthorizationRequiredError) {
2349
+ setState("needs_auth");
2350
+ }
2351
+ throw translated;
2352
+ }
2353
+ },
2354
+ auth: {
2355
+ async signIn() {
2356
+ await ensureConnected();
2357
+ },
2358
+ async signOut() {
2359
+ await mcp.clearAuth();
2360
+ _metaToolMode = null;
2361
+ setState("idle");
2362
+ },
2363
+ async handleCallback(url) {
2364
+ await mcp.handleCallback(url);
2365
+ try {
2366
+ await ensureConnected();
2367
+ } catch (err) {
2368
+ emitError(translateError(err));
2369
+ }
2370
+ },
2371
+ isCallback(url) {
2372
+ return mcp.isCallback(url);
2373
+ },
2374
+ get isAuthenticated() {
2375
+ return _state === "ready" || mcp.isConnected;
2376
+ }
2377
+ },
2378
+ integrations: {
2379
+ async list() {
2380
+ await ensureConnected();
2381
+ try {
2382
+ const { tools, errors, elicitations } = await fetchGatewayTools();
2383
+ const statuses = parseIntegrationStatus(tools, errors, elicitations);
2384
+ const errorMap = new Map(errors.map((e) => [e.serverId, e.reason]));
2385
+ return statuses.map((s) => {
2386
+ const reason = errorMap.get(s.id);
2387
+ return reason ? { ...s, reason } : s;
2388
+ });
2389
+ } catch (err) {
2390
+ const translated = translateError(err);
2391
+ if (translated instanceof AuthorizationRequiredError) {
2392
+ setState("needs_auth");
2393
+ }
2394
+ throw translated;
2395
+ }
2396
+ }
2397
+ },
2398
+ tools: {
2399
+ async list(options) {
2400
+ await ensureConnected();
2401
+ try {
2402
+ const mcpTools = await mcp.listTools();
2403
+ const nonMetaTools = mcpTools.filter(
2404
+ (t) => !META_TOOL_NAMES.has(t.name)
2405
+ );
2406
+ if (nonMetaTools.length > 0 || !hasMetaTools(mcpTools)) {
2407
+ _metaToolMode = false;
2408
+ return nonMetaTools.map((t) => ({
2409
+ id: t.name,
2410
+ name: t.name,
2411
+ description: t.description,
2412
+ inputSchema: t.inputSchema
2413
+ }));
2414
+ }
2415
+ _metaToolMode = true;
2416
+ const { tools, elicitations } = await fetchGatewayTools(
2417
+ options?.limit
2418
+ );
2419
+ if (elicitations?.length && config.onIntegrationRequired) {
2420
+ for (const e of elicitations) {
2421
+ if (e.url) {
2422
+ config.onIntegrationRequired(e.url, {
2423
+ id: e.integrationId ?? "",
2424
+ name: e.integrationName ?? e.message
2425
+ });
2426
+ }
2427
+ }
2428
+ }
2429
+ return tools.map(toKontextTool);
2430
+ } catch (err) {
2431
+ const translated = translateError(err);
2432
+ if (translated instanceof AuthorizationRequiredError) {
2433
+ setState("needs_auth");
2434
+ }
2435
+ throw translated;
2436
+ }
2437
+ },
2438
+ async execute(toolId, args) {
2439
+ await ensureConnected();
2440
+ if (_metaToolMode === null) {
2441
+ const mcpTools = await mcp.listTools();
2442
+ _metaToolMode = hasMetaTools(mcpTools);
2443
+ }
2444
+ try {
2445
+ const result = _metaToolMode ? await mcp.callTool("EXECUTE_TOOL", {
2446
+ tool_id: toolId,
2447
+ tool_arguments: args ?? {}
2448
+ }) : await mcp.callTool(toolId, args);
2449
+ return { content: extractTextContent(result), raw: result };
2450
+ } catch (err) {
2451
+ const translated = translateError(err);
2452
+ if (translated instanceof AuthorizationRequiredError) {
2453
+ setState("needs_auth");
2454
+ }
2455
+ throw translated;
2456
+ }
2457
+ }
2458
+ },
2459
+ on(event, handler) {
2460
+ if (!_listeners.has(event)) {
2461
+ _listeners.set(event, /* @__PURE__ */ new Set());
2462
+ }
2463
+ _listeners.get(event).add(handler);
2464
+ return () => {
2465
+ _listeners.get(event)?.delete(handler);
2466
+ };
2467
+ },
2468
+ get mcp() {
2469
+ return mcp;
2470
+ }
2471
+ };
2472
+ return client;
2473
+ }
2474
+ function createKontextClient(config) {
2475
+ if (config.url !== void 0) {
2476
+ if (typeof config.url !== "string" || config.url.trim().length === 0) {
2477
+ throw new ConfigError(
2478
+ "url must be a non-empty string. Omit url for hybrid mode, or provide a full MCP endpoint URL.",
2479
+ "kontext_config_invalid_url"
2480
+ );
2481
+ }
2482
+ return createSingleEndpointKontextClient(config);
2483
+ }
2484
+ return createKontextOrchestrator(config);
2485
+ }
2486
+
2487
+ // src/management/types.ts
2488
+ var TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange";
2489
+ var TOKEN_TYPE_ACCESS_TOKEN = "urn:ietf:params:oauth:token-type:access_token";
2490
+
2491
+ // src/oauth/token-exchange.ts
2492
+ async function exchangeToken(config, subjectToken, resource, scope, subjectTokenType = TOKEN_TYPE_ACCESS_TOKEN) {
2493
+ const body = new URLSearchParams();
2494
+ body.set("grant_type", TOKEN_EXCHANGE_GRANT_TYPE);
2495
+ body.set("subject_token", subjectToken);
2496
+ body.set("subject_token_type", subjectTokenType);
2497
+ body.set("resource", resource);
2498
+ const headers = {
2499
+ "Content-Type": "application/x-www-form-urlencoded"
2500
+ };
2501
+ if (config.clientSecret) {
2502
+ const credentials = Buffer.from(
2503
+ `${config.clientId}:${config.clientSecret}`
2504
+ ).toString("base64");
2505
+ headers["Authorization"] = `Basic ${credentials}`;
2506
+ } else {
2507
+ body.set("client_id", config.clientId);
2508
+ }
2509
+ const response = await fetch(config.tokenUrl, {
2510
+ method: "POST",
2511
+ headers,
2512
+ body: body.toString()
2513
+ });
2514
+ if (!response.ok) {
2515
+ let errorMessage = `Token exchange failed: ${response.status} ${response.statusText}`;
2516
+ let errorCode;
2517
+ let integrationName;
2518
+ let integrationId;
2519
+ try {
2520
+ const errorBody = await response.json();
2521
+ errorCode = errorBody.error;
2522
+ if (errorBody.error_description) {
2523
+ errorMessage = errorBody.error_description;
2524
+ } else if (errorBody.error) {
2525
+ errorMessage = `Token exchange failed: ${errorBody.error}`;
2526
+ }
2527
+ if (errorBody.integration_name || errorBody.integration_id) {
2528
+ integrationName = errorBody.integration_name;
2529
+ integrationId = errorBody.integration_id;
2530
+ }
2531
+ } catch {
2532
+ }
2533
+ throw new OAuthError(errorMessage, "kontext_oauth_token_exchange_failed", {
2534
+ errorCode,
2535
+ meta: {
2536
+ integrationName,
2537
+ integrationId
2538
+ }
2539
+ });
2540
+ }
2541
+ const tokenResponse = await response.json();
2542
+ if (!tokenResponse.access_token) {
2543
+ throw new OAuthError(
2544
+ "Token exchange response missing access_token.",
2545
+ "kontext_oauth_token_exchange_failed"
2546
+ );
2547
+ }
2548
+ if (!tokenResponse.issued_token_type) {
2549
+ throw new OAuthError(
2550
+ "Token exchange response missing issued_token_type.",
2551
+ "kontext_oauth_token_exchange_failed"
2552
+ );
2553
+ }
2554
+ if (!tokenResponse.token_type) {
2555
+ throw new OAuthError(
2556
+ "Token exchange response missing token_type.",
2557
+ "kontext_oauth_token_exchange_failed"
2558
+ );
2559
+ }
2560
+ return tokenResponse;
2561
+ }
2562
+
2563
+ // src/verify/errors.ts
2564
+ var TokenVerificationError = class _TokenVerificationError extends Error {
2565
+ code;
2566
+ constructor(code, message) {
2567
+ super(message);
2568
+ this.name = "TokenVerificationError";
2569
+ this.code = code;
2570
+ Object.setPrototypeOf(this, _TokenVerificationError.prototype);
2571
+ }
2572
+ };
2573
+
2574
+ // src/verify/jwks-client.ts
2575
+ var DEFAULT_CACHE_TTL_MS = 5 * 60 * 1e3;
2576
+ var DEFAULT_REFETCH_COOLDOWN_MS = 30 * 1e3;
2577
+ var JwksClient = class {
2578
+ jwksUrl;
2579
+ cacheTtlMs;
2580
+ refetchCooldownMs;
2581
+ customFetch;
2582
+ jwks = null;
2583
+ lastFetchAt = 0;
2584
+ lastRefreshAt = 0;
2585
+ constructor(options) {
2586
+ this.jwksUrl = new URL(options.jwksUrl);
2587
+ this.cacheTtlMs = options.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;
2588
+ this.refetchCooldownMs = options.refetchCooldownMs ?? DEFAULT_REFETCH_COOLDOWN_MS;
2589
+ this.customFetch = options.fetch;
2590
+ }
2591
+ /**
2592
+ * Get the JWKS key resolver for use with jose's jwtVerify.
2593
+ *
2594
+ * Creates the remote JWKS on first call and caches it.
2595
+ * The jose library handles internal caching and key lookup.
2596
+ */
2597
+ getKeyResolver() {
2598
+ const now = Date.now();
2599
+ if (this.jwks && now - this.lastFetchAt > this.cacheTtlMs) {
2600
+ this.jwks = null;
2601
+ }
2602
+ if (!this.jwks) {
2603
+ this.jwks = jose.createRemoteJWKSet(this.jwksUrl, {
2604
+ // jose handles caching internally, we just track our own refresh timing
2605
+ ...this.customFetch && {
2606
+ [/* @__PURE__ */ Symbol.for("fetch")]: this.customFetch
2607
+ }
2608
+ });
2609
+ this.lastFetchAt = now;
2610
+ }
2611
+ return this.jwks;
2612
+ }
2613
+ /**
2614
+ * Force refresh the JWKS cache.
2615
+ *
2616
+ * Respects the refetch cooldown to prevent rapid refetching.
2617
+ * Returns true if refresh was performed, false if cooldown not elapsed.
2618
+ */
2619
+ refresh() {
2620
+ const now = Date.now();
2621
+ if (!this.canRefresh()) {
2622
+ return false;
2623
+ }
2624
+ this.jwks = null;
2625
+ this.lastRefreshAt = now;
2626
+ return true;
2627
+ }
2628
+ /**
2629
+ * Check if a refresh is allowed (cooldown elapsed).
2630
+ */
2631
+ canRefresh() {
2632
+ return Date.now() - this.lastRefreshAt >= this.refetchCooldownMs;
2633
+ }
2634
+ /**
2635
+ * Handle unknown kid errors by attempting refresh.
2636
+ *
2637
+ * @returns TokenVerificationError if refresh not allowed or already attempted
2638
+ */
2639
+ handleUnknownKid(kid) {
2640
+ if (this.refresh()) {
2641
+ return null;
2642
+ }
2643
+ return new TokenVerificationError(
2644
+ "UNKNOWN_KID",
2645
+ `Unknown key ID: ${kid}. JWKS refresh on cooldown.`
2646
+ );
2647
+ }
2648
+ /**
2649
+ * Clear the cache, forcing a fresh fetch on next access.
2650
+ */
2651
+ clearCache() {
2652
+ this.jwks = null;
2653
+ this.lastFetchAt = 0;
2654
+ }
2655
+ };
2656
+
2657
+ // src/verify/verifier.ts
2658
+ var DEFAULT_CLOCK_TOLERANCE_SEC = 30;
2659
+ var SUPPORTED_ALGORITHMS = ["ES256", "RS256"];
2660
+ var KontextTokenVerifier = class {
2661
+ config;
2662
+ jwksClient;
2663
+ audiences;
2664
+ constructor(config) {
2665
+ this.config = {
2666
+ jwksUrl: config.jwksUrl,
2667
+ issuer: config.issuer,
2668
+ audience: config.audience,
2669
+ requiredScopes: config.requiredScopes ?? [],
2670
+ cacheTtlMs: config.cacheTtlMs ?? 5 * 60 * 1e3,
2671
+ refetchCooldownMs: config.refetchCooldownMs ?? 30 * 1e3,
2672
+ clockToleranceSec: config.clockToleranceSec ?? DEFAULT_CLOCK_TOLERANCE_SEC,
2673
+ fetch: config.fetch
2674
+ };
2675
+ this.audiences = Array.isArray(config.audience) ? config.audience : [config.audience];
2676
+ this.jwksClient = new JwksClient({
2677
+ jwksUrl: config.jwksUrl,
2678
+ cacheTtlMs: this.config.cacheTtlMs,
2679
+ refetchCooldownMs: this.config.refetchCooldownMs,
2680
+ fetch: config.fetch
2681
+ });
2682
+ }
2683
+ /**
2684
+ * Verify a JWT token.
2685
+ *
2686
+ * @param token - The JWT token string (without "Bearer " prefix)
2687
+ * @returns VerifyResult with success=true and claims, or success=false and error
2688
+ */
2689
+ async verify(token) {
2690
+ try {
2691
+ return await this.verifyInternal(token, false);
2692
+ } catch (error) {
2693
+ if (error instanceof TokenVerificationError) {
2694
+ return { success: false, error };
2695
+ }
2696
+ return {
2697
+ success: false,
2698
+ error: new TokenVerificationError(
2699
+ "INVALID_TOKEN_FORMAT",
2700
+ `Unexpected verification error: ${error.message}`
2701
+ )
2702
+ };
2703
+ }
2704
+ }
2705
+ /**
2706
+ * Verify a JWT token and return claims or null.
2707
+ * Simpler API for cases where you don't need error details.
2708
+ *
2709
+ * @param token - The JWT token string (without "Bearer " prefix)
2710
+ * @returns VerifiedTokenClaims if valid, null if invalid
2711
+ */
2712
+ async verifyOrNull(token) {
2713
+ const result = await this.verify(token);
2714
+ return result.success ? result.claims : null;
2715
+ }
2716
+ /**
2717
+ * Clear the JWKS cache, forcing a fresh fetch on next verification.
2718
+ */
2719
+ clearCache() {
2720
+ this.jwksClient.clearCache();
2721
+ }
2722
+ async verifyInternal(token, isRetry) {
2723
+ const JWKS = this.jwksClient.getKeyResolver();
2724
+ try {
2725
+ const { payload, protectedHeader } = await jose.jwtVerify(token, JWKS, {
2726
+ issuer: this.config.issuer,
2727
+ audience: this.audiences,
2728
+ clockTolerance: this.config.clockToleranceSec,
2729
+ algorithms: SUPPORTED_ALGORITHMS
2730
+ });
2731
+ const alg = protectedHeader.alg;
2732
+ if (!SUPPORTED_ALGORITHMS.includes(alg)) {
2733
+ throw new TokenVerificationError(
2734
+ "UNSUPPORTED_ALGORITHM",
2735
+ `Unsupported algorithm: ${alg}. Expected one of: ${SUPPORTED_ALGORITHMS.join(", ")}`
2736
+ );
2737
+ }
2738
+ const jwtPayload = payload;
2739
+ if (typeof jwtPayload.exp !== "number" || !Number.isFinite(jwtPayload.exp) || jwtPayload.exp <= 0) {
2740
+ throw new TokenVerificationError(
2741
+ "MISSING_CLAIMS",
2742
+ "Token missing required exp claim"
2743
+ );
2744
+ }
2745
+ const scopes = this.parseScopes(jwtPayload.scope);
2746
+ for (const required of this.config.requiredScopes) {
2747
+ if (!scopes.includes(required)) {
2748
+ throw new TokenVerificationError(
2749
+ "MISSING_SCOPE",
2750
+ `Missing required scope: ${required}`
2751
+ );
2752
+ }
2753
+ }
2754
+ const clientId = jwtPayload.client_id || jwtPayload.sub;
2755
+ if (!clientId) {
2756
+ throw new TokenVerificationError(
2757
+ "MISSING_CLAIMS",
2758
+ "Token missing client_id and sub claims"
2759
+ );
2760
+ }
2761
+ const claims = {
2762
+ sub: jwtPayload.sub || "",
2763
+ clientId,
2764
+ scopes,
2765
+ expiresAt: new Date(jwtPayload.exp * 1e3),
2766
+ jti: jwtPayload.jti,
2767
+ payload: jwtPayload
2768
+ };
2769
+ return { success: true, claims };
2770
+ } catch (error) {
2771
+ if (error instanceof jose.errors.JWKSNoMatchingKey) {
2772
+ if (!isRetry) {
2773
+ const kid = this.extractKid(token);
2774
+ const refreshError = this.jwksClient.handleUnknownKid(
2775
+ kid || "unknown"
2776
+ );
2777
+ if (!refreshError) {
2778
+ return this.verifyInternal(token, true);
2779
+ }
2780
+ return { success: false, error: refreshError };
2781
+ }
2782
+ return {
2783
+ success: false,
2784
+ error: new TokenVerificationError(
2785
+ "UNKNOWN_KID",
2786
+ "No matching key found in JWKS"
2787
+ )
2788
+ };
2789
+ }
2790
+ if (error instanceof jose.errors.JWTExpired) {
2791
+ return {
2792
+ success: false,
2793
+ error: new TokenVerificationError(
2794
+ "TOKEN_EXPIRED",
2795
+ "Token has expired"
2796
+ )
2797
+ };
2798
+ }
2799
+ if (error instanceof jose.errors.JWTClaimValidationFailed) {
2800
+ const message = error.message;
2801
+ if (message.includes("iss")) {
2802
+ const expected = Array.isArray(this.config.issuer) ? this.config.issuer.join(" or ") : this.config.issuer;
2803
+ return {
2804
+ success: false,
2805
+ error: new TokenVerificationError(
2806
+ "INVALID_ISSUER",
2807
+ `Invalid issuer: expected ${expected}`
2808
+ )
2809
+ };
2810
+ }
2811
+ if (message.includes("aud")) {
2812
+ return {
2813
+ success: false,
2814
+ error: new TokenVerificationError(
2815
+ "INVALID_AUDIENCE",
2816
+ `Invalid audience: expected one of ${this.audiences.join(", ")}`
2817
+ )
2818
+ };
2819
+ }
2820
+ if (message.includes("nbf")) {
2821
+ return {
2822
+ success: false,
2823
+ error: new TokenVerificationError(
2824
+ "TOKEN_NOT_YET_VALID",
2825
+ "Token is not yet valid (nbf claim)"
2826
+ )
2827
+ };
2828
+ }
2829
+ }
2830
+ if (error instanceof jose.errors.JWSSignatureVerificationFailed) {
2831
+ return {
2832
+ success: false,
2833
+ error: new TokenVerificationError(
2834
+ "INVALID_SIGNATURE",
2835
+ "Signature verification failed"
2836
+ )
2837
+ };
2838
+ }
2839
+ if (error instanceof jose.errors.JWSInvalid) {
2840
+ return {
2841
+ success: false,
2842
+ error: new TokenVerificationError(
2843
+ "INVALID_TOKEN_FORMAT",
2844
+ `Invalid JWS: ${error.message}`
2845
+ )
2846
+ };
2847
+ }
2848
+ if (error instanceof TokenVerificationError) {
2849
+ throw error;
2850
+ }
2851
+ throw new TokenVerificationError(
2852
+ "INVALID_TOKEN_FORMAT",
2853
+ `Verification failed: ${error.message}`
2854
+ );
2855
+ }
2856
+ }
2857
+ parseScopes(scope) {
2858
+ if (!scope) return [];
2859
+ return scope.split(" ").map((s) => s.trim()).filter(Boolean);
2860
+ }
2861
+ extractKid(token) {
2862
+ try {
2863
+ const header = jose.decodeProtectedHeader(token);
2864
+ return header.kid ?? null;
2865
+ } catch {
2866
+ return null;
2867
+ }
2868
+ }
2869
+ };
2870
+
2871
+ // src/server/sessions.ts
2872
+ var SessionManager = class _SessionManager {
2873
+ transports = /* @__PURE__ */ new Map();
2874
+ lastAccessed = /* @__PURE__ */ new Map();
2875
+ expiresAt = /* @__PURE__ */ new Map();
2876
+ cleanupInterval;
2877
+ static STALE_TIMEOUT_MS = 60 * 60 * 1e3;
2878
+ // 1 hour
2879
+ static CLEANUP_INTERVAL_MS = 5 * 60 * 1e3;
2880
+ // 5 minutes
2881
+ constructor() {
2882
+ this.cleanupInterval = setInterval(
2883
+ () => this.cleanupStaleSessions(),
2884
+ _SessionManager.CLEANUP_INTERVAL_MS
2885
+ );
2886
+ if (this.cleanupInterval.unref) {
2887
+ this.cleanupInterval.unref();
2888
+ }
2889
+ }
2890
+ getTransport(sessionId) {
2891
+ return this.transports.get(sessionId);
2892
+ }
2893
+ registerSession(sessionId, transport, callbacks, expiresAt) {
2894
+ this.transports.set(sessionId, transport);
2895
+ this.lastAccessed.set(sessionId, Date.now());
2896
+ if (expiresAt !== void 0) {
2897
+ this.expiresAt.set(sessionId, expiresAt);
2898
+ }
2899
+ transport.onclose = () => {
2900
+ this.removeSession(sessionId);
2901
+ callbacks?.onSessionClosed?.(sessionId);
2902
+ };
2903
+ }
2904
+ touchSession(sessionId) {
2905
+ if (this.transports.has(sessionId)) {
2906
+ this.lastAccessed.set(sessionId, Date.now());
2907
+ }
2908
+ }
2909
+ removeSession(sessionId) {
2910
+ this.transports.delete(sessionId);
2911
+ this.lastAccessed.delete(sessionId);
2912
+ this.expiresAt.delete(sessionId);
2913
+ }
2914
+ /**
2915
+ * Check if a session's token has expired.
2916
+ * Returns true if the token's `expiresAt` has passed.
2917
+ */
2918
+ isSessionExpired(sessionId) {
2919
+ const exp = this.expiresAt.get(sessionId);
2920
+ return exp !== void 0 && Date.now() / 1e3 >= exp;
2921
+ }
2922
+ cleanupStaleSessions() {
2923
+ const now = Date.now();
2924
+ for (const [sid, lastTime] of this.lastAccessed.entries()) {
2925
+ if (now - lastTime > _SessionManager.STALE_TIMEOUT_MS) {
2926
+ const transport = this.transports.get(sid);
2927
+ if (transport) {
2928
+ void transport.close?.();
2929
+ }
2930
+ this.removeSession(sid);
2931
+ }
2932
+ }
2933
+ }
2934
+ destroy() {
2935
+ clearInterval(this.cleanupInterval);
2936
+ for (const [sid, transport] of this.transports.entries()) {
2937
+ void transport.close?.();
2938
+ this.removeSession(sid);
2939
+ }
2940
+ }
2941
+ };
2942
+
2943
+ // src/server/kontext.ts
2944
+ var DEFAULT_API_URL = "https://api.kontext.dev";
2945
+ var METADATA_CACHE_TTL_MS = 60 * 60 * 1e3;
2946
+ var CREDENTIAL_CACHE_MAX_ENTRIES = 500;
2947
+ var RUNTIME_AUTH_CACHE_MAX_ENTRIES = 8;
2948
+ var RESOLVED_CREDENTIAL_CACHE_TTL_MS = 30 * 1e3;
2949
+ var SDK_VERSION = (() => {
2950
+ try {
2951
+ const esmRequire = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
2952
+ const pkg = esmRequire("../../package.json");
2953
+ return pkg.version ?? "unknown";
2954
+ } catch {
2955
+ return "unknown";
2956
+ }
2957
+ })();
2958
+ var Kontext = class _Kontext {
2959
+ static shutdownInstances = /* @__PURE__ */ new Set();
2960
+ static shutdownHandlersRegistered = false;
2961
+ clientId;
2962
+ clientSecret;
2963
+ apiUrl;
2964
+ tokenIssuers;
2965
+ // AS metadata: fetched lazily, cached with TTL
2966
+ oauthMetadata = null;
2967
+ metadataFetchedAt = 0;
2968
+ metadataPromise = null;
2969
+ // Token exchange caching: keyed by `${integration}\0${subjectToken}`
2970
+ credentialCache = /* @__PURE__ */ new Map();
2971
+ resolvedCredentialCache = /* @__PURE__ */ new Map();
2972
+ runtimeAuthCache = /* @__PURE__ */ new Map();
2973
+ runtimeVerifierIds = /* @__PURE__ */ new WeakMap();
2974
+ runtimeVerifierIdCounter = 0;
2975
+ // Telemetry: cached service token for event reporting
2976
+ serviceToken = null;
2977
+ serviceTokenExp = 0;
2978
+ serviceTokenPromise = null;
2979
+ // Session tracking: MCP sessionId → API agentSessionId
2980
+ agentSessionIds = /* @__PURE__ */ new Map();
2981
+ pendingSessionDisconnects = /* @__PURE__ */ new Set();
2982
+ constructor(options) {
2983
+ this.clientId = options.clientId;
2984
+ this.clientSecret = options.clientSecret ?? process.env.KONTEXT_CLIENT_SECRET;
2985
+ this.apiUrl = (options.apiUrl ?? DEFAULT_API_URL).replace(/\/$/, "");
2986
+ const rawTokenIssuers = Array.isArray(options.tokenIssuer) ? options.tokenIssuer : options.tokenIssuer ? options.tokenIssuer.split(",") : process.env.KONTEXT_TOKEN_ISSUER?.split(",");
2987
+ this.tokenIssuers = Array.from(
2988
+ new Set(rawTokenIssuers?.map((issuer) => issuer.trim()).filter(Boolean))
2989
+ );
2990
+ _Kontext.shutdownInstances.add(this);
2991
+ _Kontext.ensureShutdownHandlers();
2992
+ }
2993
+ /**
2994
+ * Cleanup method for runtimes that create/dispose SDK instances dynamically.
2995
+ * Ensures this instance can be garbage-collected by removing static references.
2996
+ */
2997
+ async destroy() {
2998
+ await this.disconnectAllSessions();
2999
+ _Kontext.shutdownInstances.delete(this);
3000
+ this.credentialCache.clear();
3001
+ this.resolvedCredentialCache.clear();
3002
+ this.oauthMetadata = null;
3003
+ this.metadataFetchedAt = 0;
3004
+ this.metadataPromise = null;
3005
+ this.serviceToken = null;
3006
+ this.serviceTokenExp = 0;
3007
+ this.serviceTokenPromise = null;
3008
+ this.agentSessionIds.clear();
3009
+ this.pendingSessionDisconnects.clear();
3010
+ }
3011
+ static ensureShutdownHandlers() {
3012
+ if (_Kontext.shutdownHandlersRegistered) return;
3013
+ const onShutdown = () => {
3014
+ for (const instance of _Kontext.shutdownInstances) {
3015
+ void instance.disconnectAllSessions();
3016
+ }
3017
+ };
3018
+ process.once("SIGINT", onShutdown);
3019
+ process.once("SIGTERM", onShutdown);
3020
+ _Kontext.shutdownHandlersRegistered = true;
3021
+ }
3022
+ // ===========================================================================
3023
+ // middleware()
3024
+ // ===========================================================================
3025
+ /**
3026
+ * Express middleware: `.well-known` metadata + bearer auth + MCP transport + sessions.
3027
+ *
3028
+ * Must be mounted at the app root (not a sub-path) because RFC 9728 requires
3029
+ * `/.well-known/oauth-protected-resource` at the root. Use `mcpPath` to set
3030
+ * the transport endpoint path.
3031
+ *
3032
+ * @param server - An `McpServer` instance for single-session use, or a
3033
+ * `() => McpServer` factory for concurrent sessions (recommended in production).
3034
+ * `McpServer.connect()` is 1:1 per the MCP spec — passing a factory ensures
3035
+ * each session gets its own instance.
3036
+ *
3037
+ * @example Factory pattern (recommended for concurrent sessions)
3038
+ * ```typescript
3039
+ * app.use(kontext.middleware(() => createServer()));
3040
+ * ```
3041
+ *
3042
+ * @example Single instance (local dev / single session)
3043
+ * ```typescript
3044
+ * app.use(kontext.middleware(server));
3045
+ * ```
3046
+ *
3047
+ * @example Custom path
3048
+ * ```typescript
3049
+ * app.use(kontext.middleware(createServer, { mcpPath: "/api/mcp" }));
3050
+ * ```
3051
+ */
3052
+ middleware(server, options) {
3053
+ const esmRequire = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
3054
+ const express = esmRequire("express");
3055
+ const router = express.Router();
3056
+ const mcpPath = options?.mcpPath ?? "/mcp";
3057
+ const sessionManager = new SessionManager();
3058
+ const omitAuth = options?.dangerouslyOmitAuth ?? false;
3059
+ router.use((_req, res, next) => {
3060
+ res.header("Access-Control-Allow-Origin", "*");
3061
+ res.header(
3062
+ "Access-Control-Allow-Headers",
3063
+ "Content-Type, Authorization, Mcp-Session-Id, Mcp-Protocol-Version, Accept"
3064
+ );
3065
+ res.header("Access-Control-Expose-Headers", "Mcp-Session-Id");
3066
+ res.header("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
3067
+ if (_req.method === "OPTIONS") {
3068
+ res.sendStatus(204);
3069
+ return;
3070
+ }
3071
+ next();
3072
+ });
3073
+ if (omitAuth) {
3074
+ console.warn(
3075
+ "[kontext] \u26A0\uFE0F Auth is disabled (dangerouslyOmitAuth). Do NOT use in production."
3076
+ );
3077
+ router.use(mcpPath, express.json({ limit: options?.bodyLimit ?? "1mb" }));
3078
+ const mcpHandler2 = this.createMcpHandler(
3079
+ server,
3080
+ sessionManager,
3081
+ null,
3082
+ options
3083
+ );
3084
+ router.post(mcpPath, mcpHandler2.post);
3085
+ router.get(mcpPath, mcpHandler2.get);
3086
+ router.delete(mcpPath, mcpHandler2.delete);
3087
+ return router;
3088
+ }
3089
+ const getRuntimeAuth = async (req) => {
3090
+ const metadata = this.applyMetadataTransform(
3091
+ await this.getOAuthMetadata(),
3092
+ options?.metadataTransform
3093
+ );
3094
+ const rsUrl = this.resolveResourceServerUrl(req, mcpPath, options);
3095
+ return this.getOrCreateRuntimeAuthContext(
3096
+ metadata,
3097
+ rsUrl,
3098
+ options?.verifier
3099
+ );
3100
+ };
3101
+ router.use(async (req, res, next) => {
3102
+ const path = req.path || req.url || "";
3103
+ const isMetadataRequest = path.startsWith("/.well-known/oauth-authorization-server") || path.startsWith("/.well-known/oauth-protected-resource");
3104
+ if (!isMetadataRequest) {
3105
+ next();
3106
+ return;
3107
+ }
3108
+ try {
3109
+ const runtimeAuth = await getRuntimeAuth(req);
3110
+ runtimeAuth.metadataRouter(req, res, next);
3111
+ } catch (error) {
3112
+ this.respondMetadataInitError(res, error);
3113
+ }
3114
+ });
3115
+ router.use(mcpPath, express.json({ limit: options?.bodyLimit ?? "1mb" }));
3116
+ const mcpHandler = this.createMcpHandler(
3117
+ server,
3118
+ sessionManager,
3119
+ getRuntimeAuth,
3120
+ options
3121
+ );
3122
+ router.post(mcpPath, mcpHandler.post);
3123
+ router.get(mcpPath, mcpHandler.get);
3124
+ router.delete(mcpPath, mcpHandler.delete);
3125
+ return router;
3126
+ }
3127
+ // ===========================================================================
3128
+ // require()
3129
+ // ===========================================================================
3130
+ /**
3131
+ * Exchange a user's access token for an integration credential.
3132
+ *
3133
+ * @param integration - Integration name (e.g., "github")
3134
+ * @param token - The user's Bearer token (from `authInfo.token`)
3135
+ * @returns Integration credential with `accessToken` and `authorization` header
3136
+ *
3137
+ * @throws {IntegrationConnectionRequiredError} User hasn't connected this integration
3138
+ * @throws {OAuthError} Token exchange failed
3139
+ */
3140
+ async require(integration, token) {
3141
+ const now = Date.now();
3142
+ this.evictExpiredCredentials(now);
3143
+ const cacheKey = `${integration}\0${token}`;
3144
+ const cached = this.credentialCache.get(cacheKey);
3145
+ if (cached && now < cached.expiresAt) {
3146
+ this.credentialCache.delete(cacheKey);
3147
+ this.credentialCache.set(cacheKey, cached);
3148
+ return cached.credential;
3149
+ }
3150
+ if (cached) {
3151
+ this.credentialCache.delete(cacheKey);
3152
+ }
3153
+ const exchangeConfig = {
3154
+ tokenUrl: `${this.apiUrl}/oauth2/token`,
3155
+ clientId: this.clientId,
3156
+ clientSecret: this.clientSecret
3157
+ };
3158
+ let response;
3159
+ try {
3160
+ response = await exchangeToken(exchangeConfig, token, integration);
3161
+ } catch (err) {
3162
+ if (err instanceof OAuthError) {
3163
+ if (err.errorCode === "integration_required" || err.message.includes("not connected") || err.message.includes("expired") && err.message.includes("reconnect")) {
3164
+ const integrationId = err.meta.integrationId || integration;
3165
+ const connectUrl = await this.fetchConnectUrl(
3166
+ token,
3167
+ integrationId,
3168
+ exchangeConfig
3169
+ );
3170
+ throw new IntegrationConnectionRequiredError(integrationId, {
3171
+ integrationName: err.meta.integrationName,
3172
+ connectUrl,
3173
+ message: err.message
3174
+ });
3175
+ }
3176
+ }
3177
+ throw err;
3178
+ }
3179
+ const credential = {
3180
+ accessToken: response.access_token,
3181
+ tokenType: response.token_type,
3182
+ authorization: `${response.token_type} ${response.access_token}`,
3183
+ expiresIn: response.expires_in,
3184
+ scope: response.scope,
3185
+ integration
3186
+ };
3187
+ if (response.expires_in) {
3188
+ const ttlMs = Math.min(response.expires_in - 60, 5 * 60) * 1e3;
3189
+ if (ttlMs > 0) {
3190
+ this.trimCacheToFit(this.credentialCache, CREDENTIAL_CACHE_MAX_ENTRIES);
3191
+ this.credentialCache.set(cacheKey, {
3192
+ credential,
3193
+ expiresAt: now + ttlMs
3194
+ });
3195
+ }
3196
+ }
3197
+ return credential;
3198
+ }
3199
+ /**
3200
+ * Resolve per-user credential key/value pairs for an internal MCP integration.
3201
+ *
3202
+ * @param integration - Integration UUID or name
3203
+ * @param token - The user's Bearer token (from `authInfo.token`)
3204
+ * @returns Decrypted credential map for the current user and integration
3205
+ *
3206
+ * @throws {IntegrationConnectionRequiredError} User has not provided required credentials
3207
+ * @throws {OAuthError} Runtime credential resolution failed
3208
+ */
3209
+ async requireCredentials(integration, token) {
3210
+ const now = Date.now();
3211
+ this.evictExpiredResolvedCredentials(now);
3212
+ const cacheKey = `${integration}\0${token}\0internal_credentials`;
3213
+ const cached = this.resolvedCredentialCache.get(cacheKey);
3214
+ if (cached && now < cached.expiresAt) {
3215
+ this.resolvedCredentialCache.delete(cacheKey);
3216
+ this.resolvedCredentialCache.set(cacheKey, cached);
3217
+ return cached.credential;
3218
+ }
3219
+ if (cached) {
3220
+ this.resolvedCredentialCache.delete(cacheKey);
3221
+ }
3222
+ const exchangeConfig = {
3223
+ tokenUrl: `${this.apiUrl}/oauth2/token`,
3224
+ clientId: this.clientId,
3225
+ clientSecret: this.clientSecret
3226
+ };
3227
+ let gatewayAccessToken = token;
3228
+ if (!this.isGatewayScopedToken(token)) {
3229
+ try {
3230
+ const exchanged = await exchangeToken(
3231
+ exchangeConfig,
3232
+ token,
3233
+ "mcp-gateway"
3234
+ );
3235
+ gatewayAccessToken = exchanged.access_token;
3236
+ } catch (err) {
3237
+ throw new OAuthError(
3238
+ "Failed to exchange subject token for runtime",
3239
+ "kontext_credentials_exchange_failed",
3240
+ {
3241
+ errorCode: "credentials_exchange_failed",
3242
+ errorDescription: err instanceof Error ? err.message : String(err ?? "unknown error")
3243
+ }
3244
+ );
3245
+ }
3246
+ }
3247
+ const integrationId = await this.resolveRuntimeIntegrationId(
3248
+ integration,
3249
+ gatewayAccessToken
3250
+ );
3251
+ const res = await fetch(
3252
+ `${this.apiUrl}/mcp/integrations/${integrationId}/credentials/resolve`,
3253
+ {
3254
+ method: "POST",
3255
+ headers: {
3256
+ Authorization: `Bearer ${gatewayAccessToken}`,
3257
+ "Content-Type": "application/json"
3258
+ },
3259
+ body: "{}"
3260
+ }
3261
+ );
3262
+ if (!res.ok) {
3263
+ const text = await res.text().catch(() => "");
3264
+ const message = text && text.trim().length > 0 ? text : `HTTP ${res.status} while resolving credentials`;
3265
+ if (res.status === 400 && message.toLowerCase().includes("credentials required")) {
3266
+ throw new IntegrationConnectionRequiredError(integrationId, {
3267
+ integrationName: String(integration),
3268
+ message
3269
+ });
3270
+ }
3271
+ throw new OAuthError(
3272
+ `Failed to resolve credentials for integration ${integrationId}`,
3273
+ "kontext_credentials_resolve_failed",
3274
+ {
3275
+ errorCode: "credentials_resolve_failed",
3276
+ errorDescription: message
3277
+ }
3278
+ );
3279
+ }
3280
+ const payload = await res.json();
3281
+ if (!payload.credentials || typeof payload.credentials !== "object" || Array.isArray(payload.credentials)) {
3282
+ throw new OAuthError(
3283
+ "Credential resolve returned invalid payload",
3284
+ "kontext_credentials_invalid_payload"
3285
+ );
3286
+ }
3287
+ const credentials = {};
3288
+ for (const [key, value] of Object.entries(payload.credentials)) {
3289
+ if (typeof value === "string") {
3290
+ credentials[key] = value;
3291
+ }
3292
+ }
3293
+ if (Object.keys(credentials).length === 0) {
3294
+ throw new IntegrationConnectionRequiredError(integrationId, {
3295
+ integrationName: String(integration),
3296
+ message: "No credentials configured for this integration"
3297
+ });
3298
+ }
3299
+ const resolved = {
3300
+ integration,
3301
+ integrationId: payload.integrationId ?? integrationId,
3302
+ credentials
3303
+ };
3304
+ this.trimCacheToFit(
3305
+ this.resolvedCredentialCache,
3306
+ CREDENTIAL_CACHE_MAX_ENTRIES
3307
+ );
3308
+ this.resolvedCredentialCache.set(cacheKey, {
3309
+ credential: resolved,
3310
+ expiresAt: now + RESOLVED_CREDENTIAL_CACHE_TTL_MS
3311
+ });
3312
+ return resolved;
3313
+ }
3314
+ getGatewayAudiences() {
3315
+ return /* @__PURE__ */ new Set([`${new URL(this.apiUrl).origin}/mcp`, "mcp-gateway"]);
3316
+ }
3317
+ isGatewayScopedToken(token) {
3318
+ const audiences = this.extractTokenAudiences(token);
3319
+ if (audiences.length === 0) {
3320
+ return false;
3321
+ }
3322
+ const gatewayAudiences = this.getGatewayAudiences();
3323
+ return audiences.some((audience) => gatewayAudiences.has(audience));
3324
+ }
3325
+ extractTokenAudiences(token) {
3326
+ const [, payloadPart] = token.split(".");
3327
+ if (!payloadPart) return [];
3328
+ try {
3329
+ const payload = JSON.parse(
3330
+ Buffer.from(payloadPart, "base64url").toString("utf8")
3331
+ );
3332
+ if (typeof payload.aud === "string") {
3333
+ return [payload.aud];
3334
+ }
3335
+ if (Array.isArray(payload.aud)) {
3336
+ return payload.aud.filter(
3337
+ (value) => typeof value === "string"
3338
+ );
3339
+ }
3340
+ } catch {
3341
+ }
3342
+ return [];
3343
+ }
3344
+ // ===========================================================================
3345
+ // Private: fetch connect URL (spec §2 — two-step init)
3346
+ // ===========================================================================
3347
+ async resolveRuntimeIntegrationId(integration, runtimeToken) {
3348
+ const raw = String(integration);
3349
+ if (this.isUuid(raw)) {
3350
+ return raw;
3351
+ }
3352
+ const res = await fetch(`${this.apiUrl}/mcp/integrations`, {
3353
+ headers: {
3354
+ Authorization: `Bearer ${runtimeToken}`
3355
+ }
3356
+ });
3357
+ if (!res.ok) {
3358
+ const text = await res.text().catch(() => "");
3359
+ throw new OAuthError(
3360
+ "Failed to resolve integration identifier",
3361
+ "kontext_integration_lookup_failed",
3362
+ {
3363
+ errorCode: "integration_lookup_failed",
3364
+ errorDescription: text || `HTTP ${res.status}`
3365
+ }
3366
+ );
3367
+ }
3368
+ const payload = await res.json();
3369
+ const items = Array.isArray(payload.items) ? payload.items : [];
3370
+ const match = items.find((item) => item.id === raw || item.name === raw);
3371
+ const integrationId = match?.id;
3372
+ if (!integrationId) {
3373
+ throw new IntegrationConnectionRequiredError(raw, {
3374
+ integrationName: raw,
3375
+ message: `Integration ${raw} is not attached to this application`
3376
+ });
3377
+ }
3378
+ return integrationId;
3379
+ }
3380
+ isUuid(value) {
3381
+ 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(
3382
+ value
3383
+ );
3384
+ }
3385
+ /**
3386
+ * Fetch a browser-openable connect URL for a missing integration.
3387
+ *
3388
+ * Per the integration-interrupt-flow spec, the SDK:
3389
+ * 1. Exchanges the user's token for a resource-scoped mcp-gateway JWT
3390
+ * 2. Calls POST /mcp/integrations/:id/oauth/init with that JWT
3391
+ * 3. Returns the `connectUrl` (intermediate endpoint with one-time token)
3392
+ *
3393
+ * The connect URL points to our own server (ticket pattern), which
3394
+ * validates the ticket, sets a browser session cookie, then redirects
3395
+ * to the actual OAuth provider.
3396
+ */
3397
+ async fetchConnectUrl(subjectToken, integrationId, exchangeConfig) {
3398
+ try {
3399
+ const gatewayToken = await exchangeToken(
3400
+ exchangeConfig,
3401
+ subjectToken,
3402
+ "mcp-gateway"
3403
+ );
3404
+ const initUrl = `${this.apiUrl}/mcp/integrations/${integrationId}/oauth/init`;
3405
+ const res = await fetch(initUrl, {
3406
+ method: "POST",
3407
+ headers: {
3408
+ Authorization: `Bearer ${gatewayToken.access_token}`,
3409
+ "Content-Type": "application/json"
3410
+ },
3411
+ body: JSON.stringify({})
3412
+ });
3413
+ if (!res.ok) {
3414
+ const text = await res.text().catch(() => "");
3415
+ console.warn(
3416
+ `[kontext] fetchConnectUrl: init endpoint returned ${res.status}: ${text}`
3417
+ );
3418
+ return void 0;
3419
+ }
3420
+ const data = await res.json();
3421
+ return data.connectUrl ?? data.authorizationUrl;
3422
+ } catch (err) {
3423
+ console.warn(
3424
+ `[kontext] fetchConnectUrl failed:`,
3425
+ err instanceof Error ? err.message : String(err)
3426
+ );
3427
+ return void 0;
3428
+ }
3429
+ }
3430
+ // ===========================================================================
3431
+ // Private: AS metadata
3432
+ // ===========================================================================
3433
+ async getOAuthMetadata() {
3434
+ const now = Date.now();
3435
+ if (this.oauthMetadata && now - this.metadataFetchedAt < METADATA_CACHE_TTL_MS) {
3436
+ return this.oauthMetadata;
3437
+ }
3438
+ if (this.metadataPromise) {
3439
+ return this.metadataPromise;
3440
+ }
3441
+ this.metadataPromise = this.fetchOAuthMetadata();
3442
+ try {
3443
+ const metadata = await this.metadataPromise;
3444
+ this.oauthMetadata = metadata;
3445
+ this.metadataFetchedAt = Date.now();
3446
+ return metadata;
3447
+ } finally {
3448
+ this.metadataPromise = null;
3449
+ }
3450
+ }
3451
+ applyMetadataTransform(metadata, metadataTransform) {
3452
+ if (!metadataTransform) {
3453
+ return metadata;
3454
+ }
3455
+ return metadataTransform(this.cloneOAuthMetadata(metadata));
3456
+ }
3457
+ cloneOAuthMetadata(metadata) {
3458
+ return JSON.parse(JSON.stringify(metadata));
3459
+ }
3460
+ async fetchOAuthMetadata() {
3461
+ const urls = [
3462
+ `${this.apiUrl}/.well-known/oauth-authorization-server`,
3463
+ `${this.apiUrl}/.well-known/openid-configuration`
3464
+ ];
3465
+ let lastError;
3466
+ for (const url of urls) {
3467
+ try {
3468
+ const res = await fetch(url);
3469
+ if (res.ok) {
3470
+ return await res.json();
3471
+ }
3472
+ } catch (err) {
3473
+ lastError = err instanceof Error ? err : new Error(String(err));
3474
+ }
3475
+ }
3476
+ throw new Error(
3477
+ `Failed to fetch AS metadata from ${this.apiUrl}: ${lastError?.message ?? "unknown error"}`
3478
+ );
3479
+ }
3480
+ resolveResourceServerUrl(req, mcpPath, options) {
3481
+ if (options?.resourceServerUrl) {
3482
+ return new URL(options.resourceServerUrl);
3483
+ }
3484
+ const host = req.get("host");
3485
+ if (!host) {
3486
+ throw new Error(
3487
+ "Missing Host header. Set middleware({ resourceServerUrl }) to a trusted public URL."
3488
+ );
3489
+ }
3490
+ return new URL(`${req.protocol}://${host}${mcpPath}`);
3491
+ }
3492
+ getOrCreateRuntimeAuthContext(metadata, rsUrl, customVerifier) {
3493
+ const key = this.getRuntimeAuthCacheKey(rsUrl, customVerifier);
3494
+ const cached = this.runtimeAuthCache.get(key);
3495
+ if (cached) {
3496
+ this.runtimeAuthCache.delete(key);
3497
+ this.runtimeAuthCache.set(key, cached);
3498
+ return cached;
3499
+ }
3500
+ const proxiedMetadata = { ...metadata, issuer: `${rsUrl.origin}/` };
3501
+ const metadataRouter = router_js.mcpAuthMetadataRouter({
3502
+ oauthMetadata: proxiedMetadata,
3503
+ resourceServerUrl: rsUrl
3504
+ });
3505
+ const resourceMetadataUrl = router_js.getOAuthProtectedResourceMetadataUrl(rsUrl);
3506
+ const verifier = customVerifier ?? this.createTokenVerifier(metadata, rsUrl);
3507
+ const runtimeAuth = {
3508
+ metadataRouter,
3509
+ bearerAuth: bearerAuth_js.requireBearerAuth({
3510
+ verifier,
3511
+ resourceMetadataUrl
3512
+ })
3513
+ };
3514
+ this.trimCacheToFit(this.runtimeAuthCache, RUNTIME_AUTH_CACHE_MAX_ENTRIES);
3515
+ this.runtimeAuthCache.set(key, runtimeAuth);
3516
+ return runtimeAuth;
3517
+ }
3518
+ getRuntimeAuthCacheKey(rsUrl, customVerifier) {
3519
+ if (!customVerifier) {
3520
+ return `${rsUrl.href}\0default`;
3521
+ }
3522
+ let verifierId = this.runtimeVerifierIds.get(customVerifier);
3523
+ if (verifierId === void 0) {
3524
+ verifierId = ++this.runtimeVerifierIdCounter;
3525
+ this.runtimeVerifierIds.set(customVerifier, verifierId);
3526
+ }
3527
+ return `${rsUrl.href}\0custom:${verifierId}`;
3528
+ }
3529
+ respondMetadataInitError(res, error) {
3530
+ const message = error instanceof Error ? error.message : String(error);
3531
+ console.error(`[kontext] Failed to fetch AS metadata: ${message}`);
3532
+ if (res.headersSent) return;
3533
+ res.status(503).json({
3534
+ error: "service_unavailable",
3535
+ error_description: "Failed to fetch authorization server metadata. Retry later."
3536
+ });
3537
+ }
3538
+ evictExpiredCredentials(now) {
3539
+ for (const [key, value] of this.credentialCache.entries()) {
3540
+ if (value.expiresAt <= now) {
3541
+ this.credentialCache.delete(key);
3542
+ }
3543
+ }
3544
+ }
3545
+ evictExpiredResolvedCredentials(now) {
3546
+ for (const [key, value] of this.resolvedCredentialCache.entries()) {
3547
+ if (value.expiresAt <= now) {
3548
+ this.resolvedCredentialCache.delete(key);
3549
+ }
3550
+ }
3551
+ }
3552
+ trimCacheToFit(cache, maxEntries) {
3553
+ while (cache.size >= maxEntries) {
3554
+ const oldestKey = cache.keys().next().value;
3555
+ if (!oldestKey) break;
3556
+ cache.delete(oldestKey);
3557
+ }
3558
+ }
3559
+ // ===========================================================================
3560
+ // Private: token verifier
3561
+ // ===========================================================================
3562
+ createTokenVerifier(metadata, resourceUrl) {
3563
+ const metadataRaw = metadata;
3564
+ const jwksUri = metadataRaw.jwks_uri ?? `${this.apiUrl}/.well-known/jwks.json`;
3565
+ const clientId = this.clientId;
3566
+ const issuers = Array.from(
3567
+ new Set(
3568
+ [metadata.issuer, ...this.tokenIssuers].filter(
3569
+ (issuer2) => typeof issuer2 === "string" && !!issuer2
3570
+ )
3571
+ )
3572
+ );
3573
+ if (!issuers.length) {
3574
+ throw new Error("OAuth metadata missing issuer");
3575
+ }
3576
+ const issuer = issuers.length === 1 ? issuers[0] : issuers;
3577
+ const verifier = new KontextTokenVerifier({
3578
+ jwksUrl: jwksUri,
3579
+ issuer,
3580
+ audience: resourceUrl.href
3581
+ });
3582
+ return {
3583
+ async verifyAccessToken(token) {
3584
+ const result = await verifier.verify(token);
3585
+ if (!result.success) {
3586
+ throw new errors_js.InvalidTokenError(
3587
+ `Token verification failed: ${result.error.message}`
3588
+ );
3589
+ }
3590
+ const { claims } = result;
3591
+ const payload = claims.payload;
3592
+ const ext = payload.ext ?? {};
3593
+ return {
3594
+ token,
3595
+ clientId: claims.clientId ?? clientId,
3596
+ scopes: claims.scopes,
3597
+ expiresAt: Math.floor(claims.expiresAt.getTime() / 1e3),
3598
+ extra: {
3599
+ ...ext,
3600
+ sub: claims.sub,
3601
+ email: payload.email ?? ext.email
3602
+ }
3603
+ };
3604
+ }
3605
+ };
3606
+ }
3607
+ // ===========================================================================
3608
+ // Private: telemetry
3609
+ // ===========================================================================
3610
+ async getServiceToken() {
3611
+ if (this.serviceToken && Date.now() < this.serviceTokenExp - 3e4) {
3612
+ return this.serviceToken;
3613
+ }
3614
+ if (this.serviceTokenPromise) {
3615
+ return this.serviceTokenPromise;
3616
+ }
3617
+ this.serviceTokenPromise = (async () => {
3618
+ const res = await fetch(`${this.apiUrl}/oauth2/token`, {
3619
+ method: "POST",
3620
+ headers: {
3621
+ "Content-Type": "application/x-www-form-urlencoded",
3622
+ Authorization: `Basic ${Buffer.from(this.clientId + ":" + this.clientSecret).toString("base64")}`
3623
+ },
3624
+ body: "grant_type=client_credentials"
3625
+ });
3626
+ if (!res.ok) {
3627
+ const text = await res.text().catch(() => "");
3628
+ throw new Error(
3629
+ `[kontext:telemetry] client_credentials grant failed: HTTP ${res.status} ${text}`
3630
+ );
3631
+ }
3632
+ const data = await res.json();
3633
+ this.serviceToken = data.access_token;
3634
+ this.serviceTokenExp = Date.now() + data.expires_in * 1e3;
3635
+ return data.access_token;
3636
+ })();
3637
+ try {
3638
+ return await this.serviceTokenPromise;
3639
+ } finally {
3640
+ this.serviceTokenPromise = null;
3641
+ }
3642
+ }
3643
+ reportEvent(event) {
3644
+ if (!this.clientSecret || !event.sessionId) return;
3645
+ this.getServiceToken().then(
3646
+ (token) => fetch(`${this.apiUrl}/api/v1/mcp-events`, {
3647
+ method: "POST",
3648
+ headers: {
3649
+ "Content-Type": "application/json",
3650
+ Authorization: `Bearer ${token}`
3651
+ },
3652
+ body: JSON.stringify({
3653
+ ...event,
3654
+ agentId: this.clientId,
3655
+ clientId: this.clientId,
3656
+ clientVersion: SDK_VERSION
3657
+ })
3658
+ }).then((res) => {
3659
+ if (!res.ok) {
3660
+ console.warn(
3661
+ `[kontext:telemetry] event report failed: HTTP ${res.status}`
3662
+ );
3663
+ }
3664
+ })
3665
+ ).catch((err) => {
3666
+ console.warn(
3667
+ `[kontext:telemetry] error:`,
3668
+ err instanceof Error ? err.message : String(err)
3669
+ );
3670
+ });
3671
+ }
3672
+ // ===========================================================================
3673
+ // Private: session lifecycle
3674
+ // ===========================================================================
3675
+ createAgentSession(userToken, mcpSessionId, metadata) {
3676
+ if (!this.clientSecret || !userToken) return;
3677
+ const tokenIdentifier = crypto$1.createHash("sha256").update(userToken).digest("hex");
3678
+ this.getServiceToken().then(
3679
+ (token) => fetch(`${this.apiUrl}/api/v1/agent-sessions`, {
3680
+ method: "POST",
3681
+ headers: {
3682
+ "Content-Type": "application/json",
3683
+ Authorization: `Bearer ${token}`
3684
+ },
3685
+ body: JSON.stringify({
3686
+ tokenIdentifier,
3687
+ hostname: metadata?.hostname,
3688
+ userAgent: metadata?.userAgent,
3689
+ clientInfo: metadata?.clientInfo,
3690
+ tokenExpiresAt: metadata?.tokenExpiresAt ? new Date(metadata.tokenExpiresAt * 1e3).toISOString() : void 0
3691
+ })
3692
+ }).then(async (res) => {
3693
+ if (res.ok) {
3694
+ const data = await res.json();
3695
+ if (this.pendingSessionDisconnects.delete(mcpSessionId)) {
3696
+ this.disconnectAgentSessionByAgentSessionId(
3697
+ data.sessionId,
3698
+ token
3699
+ );
3700
+ return;
3701
+ }
3702
+ this.agentSessionIds.set(mcpSessionId, data.sessionId);
3703
+ } else {
3704
+ this.pendingSessionDisconnects.delete(mcpSessionId);
3705
+ console.warn(
3706
+ `[kontext:sessions] create failed: HTTP ${res.status}`
3707
+ );
3708
+ }
3709
+ })
3710
+ ).catch((err) => {
3711
+ this.pendingSessionDisconnects.delete(mcpSessionId);
3712
+ console.warn(
3713
+ `[kontext:sessions] error:`,
3714
+ err instanceof Error ? err.message : String(err)
3715
+ );
3716
+ });
3717
+ }
3718
+ disconnectAgentSessionByAgentSessionId(agentSessionId, serviceToken) {
3719
+ if (!this.clientSecret) return;
3720
+ const tokenPromise = serviceToken ? Promise.resolve(serviceToken) : this.getServiceToken();
3721
+ tokenPromise.then(
3722
+ (token) => fetch(
3723
+ `${this.apiUrl}/api/v1/agent-sessions/${agentSessionId}/disconnect`,
3724
+ {
3725
+ method: "POST",
3726
+ headers: { Authorization: `Bearer ${token}` }
3727
+ }
3728
+ )
3729
+ ).catch(() => {
3730
+ });
3731
+ }
3732
+ disconnectAgentSession(mcpSessionId) {
3733
+ if (!this.clientSecret) return;
3734
+ const agentSessionId = this.agentSessionIds.get(mcpSessionId);
3735
+ this.agentSessionIds.delete(mcpSessionId);
3736
+ if (!agentSessionId) {
3737
+ this.pendingSessionDisconnects.add(mcpSessionId);
3738
+ return;
3739
+ }
3740
+ this.pendingSessionDisconnects.delete(mcpSessionId);
3741
+ this.disconnectAgentSessionByAgentSessionId(agentSessionId);
3742
+ }
3743
+ async disconnectAllSessions() {
3744
+ if (!this.clientSecret) return;
3745
+ if (this.agentSessionIds.size === 0) {
3746
+ this.pendingSessionDisconnects.clear();
3747
+ return;
3748
+ }
3749
+ try {
3750
+ const token = await this.getServiceToken();
3751
+ await Promise.allSettled(
3752
+ [...this.agentSessionIds.values()].map(
3753
+ (agentSessionId) => fetch(
3754
+ `${this.apiUrl}/api/v1/agent-sessions/${agentSessionId}/disconnect`,
3755
+ {
3756
+ method: "POST",
3757
+ headers: { Authorization: `Bearer ${token}` }
3758
+ }
3759
+ )
3760
+ )
3761
+ );
3762
+ } catch {
3763
+ }
3764
+ this.agentSessionIds.clear();
3765
+ this.pendingSessionDisconnects.clear();
3766
+ }
3767
+ // ===========================================================================
3768
+ // Private: MCP transport handlers
3769
+ // ===========================================================================
3770
+ async runBearerAuth(bearerAuth, req, res) {
3771
+ await new Promise((resolve, reject) => {
3772
+ let settled = false;
3773
+ let nextCalled = false;
3774
+ const cleanup = () => {
3775
+ res.removeListener("finish", onResponseDone);
3776
+ res.removeListener("close", onResponseDone);
3777
+ };
3778
+ const settleResolve = () => {
3779
+ if (settled) return;
3780
+ settled = true;
3781
+ cleanup();
3782
+ resolve();
3783
+ };
3784
+ const settleReject = (err) => {
3785
+ if (settled) return;
3786
+ settled = true;
3787
+ cleanup();
3788
+ reject(err instanceof Error ? err : new Error(String(err)));
3789
+ };
3790
+ const onResponseDone = () => {
3791
+ settleResolve();
3792
+ };
3793
+ res.once("finish", onResponseDone);
3794
+ res.once("close", onResponseDone);
3795
+ let middlewareResult;
3796
+ try {
3797
+ middlewareResult = bearerAuth(req, res, (err) => {
3798
+ nextCalled = true;
3799
+ if (err) {
3800
+ settleReject(err);
3801
+ return;
3802
+ }
3803
+ settleResolve();
3804
+ });
3805
+ } catch (err) {
3806
+ settleReject(err);
3807
+ return;
3808
+ }
3809
+ void Promise.resolve(middlewareResult).then(
3810
+ () => {
3811
+ if (!nextCalled && res.headersSent) {
3812
+ settleResolve();
3813
+ }
3814
+ },
3815
+ (err) => {
3816
+ settleReject(err);
3817
+ }
3818
+ );
3819
+ });
3820
+ }
3821
+ createMcpHandler(server, sessionManager, getRuntimeAuth, options) {
3822
+ const callbacks = {
3823
+ onSessionClosed: (sessionId) => {
3824
+ options?.onSessionClosed?.(sessionId);
3825
+ this.disconnectAgentSession(sessionId);
3826
+ }
3827
+ };
3828
+ const post = async (req, res) => {
3829
+ const traceId = crypto.randomUUID();
3830
+ const authReq = req;
3831
+ if (getRuntimeAuth) {
3832
+ let bearerAuth;
3833
+ try {
3834
+ const runtimeAuth = await getRuntimeAuth(req);
3835
+ bearerAuth = runtimeAuth.bearerAuth;
3836
+ } catch (error) {
3837
+ this.respondMetadataInitError(res, error);
3838
+ return;
3839
+ }
3840
+ await this.runBearerAuth(bearerAuth, req, res);
3841
+ const sessionId2 = req.headers["mcp-session-id"];
3842
+ if (sessionId2) {
3843
+ if (res.headersSent) {
3844
+ this.reportEvent({
3845
+ eventType: "auth_error",
3846
+ traceId,
3847
+ sessionId: sessionId2,
3848
+ durationMs: 0,
3849
+ status: "error_auth"
3850
+ });
3851
+ return;
3852
+ }
3853
+ if (authReq.auth) {
3854
+ this.reportEvent({
3855
+ eventType: "auth_ok",
3856
+ traceId,
3857
+ ownerUserId: authReq.auth.extra?.sub,
3858
+ sessionId: sessionId2,
3859
+ durationMs: 0,
3860
+ status: "ok"
3861
+ });
3862
+ }
3863
+ } else if (res.headersSent) {
3864
+ return;
3865
+ }
3866
+ }
3867
+ const sessionId = req.headers["mcp-session-id"];
3868
+ if (sessionId) {
3869
+ const transport2 = sessionManager.getTransport(sessionId);
3870
+ if (transport2) {
3871
+ sessionManager.touchSession(sessionId);
3872
+ await transport2.handleRequest(req, res, req.body);
3873
+ return;
3874
+ }
3875
+ }
3876
+ if (!types_js.isInitializeRequest(req.body)) {
3877
+ res.status(400).json({
3878
+ jsonrpc: "2.0",
3879
+ error: {
3880
+ code: -32e3,
3881
+ message: sessionId ? `Session ${sessionId} not found` : "No valid session ID provided"
3882
+ },
3883
+ id: null
3884
+ });
3885
+ return;
3886
+ }
3887
+ const authInfo = authReq.auth;
3888
+ const transport = new streamableHttp_js.StreamableHTTPServerTransport({
3889
+ sessionIdGenerator: () => crypto.randomUUID(),
3890
+ onsessioninitialized: (sid) => {
3891
+ sessionManager.registerSession(
3892
+ sid,
3893
+ transport,
3894
+ callbacks,
3895
+ authInfo?.expiresAt
3896
+ );
3897
+ options?.onSessionInitialized?.(sid, authInfo, transport);
3898
+ this.reportEvent({
3899
+ eventType: "initialize",
3900
+ traceId,
3901
+ sessionId: sid,
3902
+ ownerUserId: authInfo?.extra?.sub,
3903
+ durationMs: 0,
3904
+ status: "ok"
3905
+ });
3906
+ this.createAgentSession(authInfo?.token, sid, {
3907
+ hostname: req.headers["x-forwarded-for"],
3908
+ userAgent: req.headers["user-agent"],
3909
+ tokenExpiresAt: authInfo?.expiresAt
3910
+ });
3911
+ }
3912
+ });
3913
+ const originalHandle = transport.handleRequest.bind(transport);
3914
+ transport.handleRequest = async (wrappedReq, wrappedRes, parsedBody) => {
3915
+ const reqTraceId = wrappedReq === req ? traceId : crypto.randomUUID();
3916
+ const sid = wrappedReq.headers["mcp-session-id"] ?? transport.sessionId;
3917
+ const start = Date.now();
3918
+ try {
3919
+ await originalHandle(wrappedReq, wrappedRes, parsedBody);
3920
+ if (parsedBody?.method === "tools/call") {
3921
+ this.reportEvent({
3922
+ eventType: "execute_tool",
3923
+ traceId: reqTraceId,
3924
+ toolName: parsedBody.params?.name,
3925
+ durationMs: Date.now() - start,
3926
+ sessionId: sid,
3927
+ ownerUserId: authInfo?.extra?.sub,
3928
+ status: "ok",
3929
+ requestJson: parsedBody.params
3930
+ });
3931
+ } else if (parsedBody?.method === "tools/list") {
3932
+ this.reportEvent({
3933
+ eventType: "search_tools",
3934
+ traceId: reqTraceId,
3935
+ durationMs: Date.now() - start,
3936
+ sessionId: sid,
3937
+ ownerUserId: authInfo?.extra?.sub,
3938
+ status: "ok"
3939
+ });
3940
+ }
3941
+ } catch (err) {
3942
+ if (parsedBody?.method === "tools/call") {
3943
+ this.reportEvent({
3944
+ eventType: "execute_tool",
3945
+ traceId: reqTraceId,
3946
+ toolName: parsedBody.params?.name,
3947
+ durationMs: Date.now() - start,
3948
+ sessionId: sid,
3949
+ ownerUserId: authInfo?.extra?.sub,
3950
+ status: "error_remote",
3951
+ errorMessage: err instanceof Error ? err.message : String(err)
3952
+ });
3953
+ } else if (parsedBody?.method === "tools/list") {
3954
+ this.reportEvent({
3955
+ eventType: "search_tools",
3956
+ traceId: reqTraceId,
3957
+ durationMs: Date.now() - start,
3958
+ sessionId: sid,
3959
+ ownerUserId: authInfo?.extra?.sub,
3960
+ status: "error_remote",
3961
+ errorMessage: err instanceof Error ? err.message : String(err)
3962
+ });
3963
+ }
3964
+ throw err;
3965
+ }
3966
+ };
3967
+ const mcpServer = typeof server === "function" ? server() : server;
3968
+ await mcpServer.connect(transport);
3969
+ await transport.handleRequest(req, res, req.body);
3970
+ };
3971
+ const get = async (req, res) => {
3972
+ if (getRuntimeAuth) {
3973
+ let bearerAuth;
3974
+ try {
3975
+ const runtimeAuth = await getRuntimeAuth(req);
3976
+ bearerAuth = runtimeAuth.bearerAuth;
3977
+ } catch (error) {
3978
+ this.respondMetadataInitError(res, error);
3979
+ return;
3980
+ }
3981
+ await this.runBearerAuth(bearerAuth, req, res);
3982
+ if (res.headersSent) {
3983
+ return;
3984
+ }
3985
+ }
3986
+ const sessionId = req.headers["mcp-session-id"] || req.headers["Mcp-Session-Id"];
3987
+ if (!sessionId) {
3988
+ res.status(400).json({ error: "Missing Mcp-Session-Id header" });
3989
+ return;
3990
+ }
3991
+ const transport = sessionManager.getTransport(sessionId);
3992
+ if (!transport) {
3993
+ res.status(400).json({ error: "Session not found" });
3994
+ return;
3995
+ }
3996
+ sessionManager.touchSession(sessionId);
3997
+ await transport.handleRequest(req, res);
3998
+ };
3999
+ const del = async (req, res) => {
4000
+ if (getRuntimeAuth) {
4001
+ let bearerAuth;
4002
+ try {
4003
+ const runtimeAuth = await getRuntimeAuth(req);
4004
+ bearerAuth = runtimeAuth.bearerAuth;
4005
+ } catch (error) {
4006
+ this.respondMetadataInitError(res, error);
4007
+ return;
4008
+ }
4009
+ await this.runBearerAuth(bearerAuth, req, res);
4010
+ if (res.headersSent) {
4011
+ return;
4012
+ }
4013
+ }
4014
+ const sessionId = req.headers["mcp-session-id"] || req.headers["Mcp-Session-Id"];
4015
+ if (!sessionId) {
4016
+ res.status(400).json({ error: "Missing Mcp-Session-Id header" });
4017
+ return;
4018
+ }
4019
+ const transport = sessionManager.getTransport(sessionId);
4020
+ if (!transport) {
4021
+ res.status(400).json({ error: "Session not found" });
4022
+ return;
4023
+ }
4024
+ await transport.handleRequest(req, res);
4025
+ };
4026
+ return { post, get, delete: del };
4027
+ }
4028
+ };
4029
+
4030
+ exports.AuthorizationRequiredError = AuthorizationRequiredError;
4031
+ exports.ConfigError = ConfigError;
4032
+ exports.HttpError = HttpError;
4033
+ exports.IntegrationConnectionRequiredError = IntegrationConnectionRequiredError;
4034
+ exports.Kontext = Kontext;
4035
+ exports.KontextError = KontextError;
4036
+ exports.KontextTokenVerifier = KontextTokenVerifier;
4037
+ exports.NetworkError = NetworkError;
4038
+ exports.OAuthError = OAuthError;
4039
+ exports.createKontextClient = createKontextClient;
4040
+ exports.createKontextOrchestrator = createKontextOrchestrator;
4041
+ exports.isKontextError = isKontextError;
4042
+ exports.isNetworkError = isNetworkError;
4043
+ exports.isUnauthorizedError = isUnauthorizedError;
4044
+ exports.parseHttpError = parseHttpError;
4045
+ //# sourceMappingURL=index.cjs.map
4046
+ //# sourceMappingURL=index.cjs.map