@kontext-dev/js-sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +70 -0
  2. package/dist/adapters/ai/index.cjs +175 -0
  3. package/dist/adapters/ai/index.cjs.map +1 -0
  4. package/dist/adapters/ai/index.d.cts +51 -0
  5. package/dist/adapters/ai/index.d.ts +51 -0
  6. package/dist/adapters/ai/index.js +173 -0
  7. package/dist/adapters/ai/index.js.map +1 -0
  8. package/dist/adapters/cloudflare/index.cjs +598 -0
  9. package/dist/adapters/cloudflare/index.cjs.map +1 -0
  10. package/dist/adapters/cloudflare/index.d.cts +214 -0
  11. package/dist/adapters/cloudflare/index.d.ts +214 -0
  12. package/dist/adapters/cloudflare/index.js +594 -0
  13. package/dist/adapters/cloudflare/index.js.map +1 -0
  14. package/dist/adapters/cloudflare/react.cjs +156 -0
  15. package/dist/adapters/cloudflare/react.cjs.map +1 -0
  16. package/dist/adapters/cloudflare/react.d.cts +68 -0
  17. package/dist/adapters/cloudflare/react.d.ts +68 -0
  18. package/dist/adapters/cloudflare/react.js +152 -0
  19. package/dist/adapters/cloudflare/react.js.map +1 -0
  20. package/dist/adapters/react/index.cjs +146 -0
  21. package/dist/adapters/react/index.cjs.map +1 -0
  22. package/dist/adapters/react/index.d.cts +103 -0
  23. package/dist/adapters/react/index.d.ts +103 -0
  24. package/dist/adapters/react/index.js +142 -0
  25. package/dist/adapters/react/index.js.map +1 -0
  26. package/dist/client/index.cjs +2415 -0
  27. package/dist/client/index.cjs.map +1 -0
  28. package/dist/client/index.d.cts +125 -0
  29. package/dist/client/index.d.ts +125 -0
  30. package/dist/client/index.js +2412 -0
  31. package/dist/client/index.js.map +1 -0
  32. package/dist/errors.cjs +213 -0
  33. package/dist/errors.cjs.map +1 -0
  34. package/dist/errors.d.cts +161 -0
  35. package/dist/errors.d.ts +161 -0
  36. package/dist/errors.js +201 -0
  37. package/dist/errors.js.map +1 -0
  38. package/dist/index-D5hS5PGn.d.ts +54 -0
  39. package/dist/index-DcL4a5Vq.d.cts +54 -0
  40. package/dist/index.cjs +4046 -0
  41. package/dist/index.cjs.map +1 -0
  42. package/dist/index.d.cts +15 -0
  43. package/dist/index.d.ts +15 -0
  44. package/dist/index.js +4029 -0
  45. package/dist/index.js.map +1 -0
  46. package/dist/kontext-CgIBANFo.d.cts +308 -0
  47. package/dist/kontext-CgIBANFo.d.ts +308 -0
  48. package/dist/management/index.cjs +867 -0
  49. package/dist/management/index.cjs.map +1 -0
  50. package/dist/management/index.d.cts +467 -0
  51. package/dist/management/index.d.ts +467 -0
  52. package/dist/management/index.js +855 -0
  53. package/dist/management/index.js.map +1 -0
  54. package/dist/mcp/index.cjs +799 -0
  55. package/dist/mcp/index.cjs.map +1 -0
  56. package/dist/mcp/index.d.cts +231 -0
  57. package/dist/mcp/index.d.ts +231 -0
  58. package/dist/mcp/index.js +797 -0
  59. package/dist/mcp/index.js.map +1 -0
  60. package/dist/oauth/index.cjs +418 -0
  61. package/dist/oauth/index.cjs.map +1 -0
  62. package/dist/oauth/index.d.cts +235 -0
  63. package/dist/oauth/index.d.ts +235 -0
  64. package/dist/oauth/index.js +414 -0
  65. package/dist/oauth/index.js.map +1 -0
  66. package/dist/server/index.cjs +1634 -0
  67. package/dist/server/index.cjs.map +1 -0
  68. package/dist/server/index.d.cts +10 -0
  69. package/dist/server/index.d.ts +10 -0
  70. package/dist/server/index.js +1629 -0
  71. package/dist/server/index.js.map +1 -0
  72. package/dist/types-CzhnlJHW.d.cts +397 -0
  73. package/dist/types-CzhnlJHW.d.ts +397 -0
  74. package/dist/types-RIzHnRpk.d.cts +23 -0
  75. package/dist/types-RIzHnRpk.d.ts +23 -0
  76. package/dist/verifier-CoJmYiw3.d.cts +109 -0
  77. package/dist/verifier-CoJmYiw3.d.ts +109 -0
  78. package/dist/verify/index.cjs +319 -0
  79. package/dist/verify/index.cjs.map +1 -0
  80. package/dist/verify/index.d.cts +63 -0
  81. package/dist/verify/index.d.ts +63 -0
  82. package/dist/verify/index.js +315 -0
  83. package/dist/verify/index.js.map +1 -0
  84. package/package.json +221 -0
@@ -0,0 +1,2415 @@
1
+ 'use strict';
2
+
3
+ var index_js = require('@modelcontextprotocol/sdk/client/index.js');
4
+ var streamableHttp_js = require('@modelcontextprotocol/sdk/client/streamableHttp.js');
5
+ var types_js = require('@modelcontextprotocol/sdk/types.js');
6
+ var crypto = require('crypto');
7
+
8
+ // src/mcp/client.ts
9
+
10
+ // src/storage/memory.ts
11
+ var MemoryStorage = class {
12
+ store = /* @__PURE__ */ new Map();
13
+ async getJson(key) {
14
+ const value = this.store.get(key);
15
+ if (value === void 0) {
16
+ return void 0;
17
+ }
18
+ return JSON.parse(JSON.stringify(value));
19
+ }
20
+ async setJson(key, value) {
21
+ if (value === void 0) {
22
+ this.store.delete(key);
23
+ } else {
24
+ this.store.set(key, JSON.parse(JSON.stringify(value)));
25
+ }
26
+ }
27
+ /**
28
+ * Clear all stored data
29
+ */
30
+ clear() {
31
+ this.store.clear();
32
+ }
33
+ /**
34
+ * Get the number of stored items
35
+ */
36
+ get size() {
37
+ return this.store.size;
38
+ }
39
+ /**
40
+ * Check if a key exists
41
+ */
42
+ has(key) {
43
+ return this.store.has(key);
44
+ }
45
+ /**
46
+ * Get all keys (useful for debugging)
47
+ */
48
+ keys() {
49
+ return Array.from(this.store.keys());
50
+ }
51
+ };
52
+
53
+ // src/storage/types.ts
54
+ function createStorageKey(applicationClientId, sessionKey, ...parts) {
55
+ const namespace = sessionKey ? `kontext:${applicationClientId}:${sessionKey}` : `kontext:${applicationClientId}`;
56
+ return [namespace, ...parts].join(":");
57
+ }
58
+ var StorageKeys = {
59
+ // Existing keys
60
+ TOKENS: "tokens",
61
+ CODE_VERIFIER: "code_verifier",
62
+ STATE: "state",
63
+ // Pattern B (RFC 8693 Token Exchange) keys
64
+ /** Identity tokens (no audience) */
65
+ IDENTITY_TOKENS: "identity_tokens",
66
+ /** Prefix for resource-scoped tokens */
67
+ RESOURCE_TOKENS: "resource_tokens"
68
+ };
69
+ function resourceTokenKey(resource) {
70
+ return `${StorageKeys.RESOURCE_TOKENS}:${resource}`;
71
+ }
72
+
73
+ // src/errors.ts
74
+ var KontextError = class extends Error {
75
+ /** Brand field for type narrowing without instanceof */
76
+ kontextError = true;
77
+ /** Machine-readable error code, always prefixed with `kontext_` */
78
+ code;
79
+ /** HTTP status code when applicable */
80
+ statusCode;
81
+ /** Auto-generated link to error documentation */
82
+ docsUrl;
83
+ /** Server request ID for debugging / support escalation */
84
+ requestId;
85
+ /** Contextual metadata bag (integration IDs, param names, etc.) */
86
+ meta;
87
+ constructor(message, code, options) {
88
+ super(message, { cause: options?.cause });
89
+ this.name = "KontextError";
90
+ this.code = code;
91
+ this.statusCode = options?.statusCode;
92
+ this.requestId = options?.requestId;
93
+ this.meta = options?.meta ?? {};
94
+ this.docsUrl = `https://docs.kontext.dev/errors/${code}`;
95
+ Object.setPrototypeOf(this, new.target.prototype);
96
+ }
97
+ toJSON() {
98
+ return {
99
+ name: this.name,
100
+ code: this.code,
101
+ message: this.message,
102
+ statusCode: this.statusCode,
103
+ docsUrl: this.docsUrl,
104
+ requestId: this.requestId,
105
+ meta: Object.keys(this.meta).length > 0 ? this.meta : void 0
106
+ };
107
+ }
108
+ toString() {
109
+ const parts = [`[${this.code}] ${this.message}`];
110
+ if (this.docsUrl) parts.push(`Docs: ${this.docsUrl}`);
111
+ if (this.requestId) parts.push(`Request ID: ${this.requestId}`);
112
+ return parts.join("\n");
113
+ }
114
+ };
115
+ function isKontextError(err) {
116
+ return typeof err === "object" && err !== null && err.kontextError === true;
117
+ }
118
+ var AuthorizationRequiredError = class extends KontextError {
119
+ authorizationUrl;
120
+ constructor(message = "Authorization required. Complete the OAuth flow to continue.", options) {
121
+ super(message, "kontext_authorization_required", {
122
+ statusCode: 401,
123
+ ...options
124
+ });
125
+ this.name = "AuthorizationRequiredError";
126
+ this.authorizationUrl = options?.authorizationUrl;
127
+ }
128
+ };
129
+ var OAuthError = class extends KontextError {
130
+ errorCode;
131
+ errorDescription;
132
+ constructor(message, code, options) {
133
+ super(message, code, {
134
+ statusCode: options?.statusCode ?? 400,
135
+ ...options
136
+ });
137
+ this.name = "OAuthError";
138
+ this.errorCode = options?.errorCode;
139
+ this.errorDescription = options?.errorDescription;
140
+ }
141
+ };
142
+ var IntegrationConnectionRequiredError = class extends KontextError {
143
+ integrationId;
144
+ integrationName;
145
+ connectUrl;
146
+ constructor(integrationId, options) {
147
+ super(
148
+ options?.message ?? `Connection to integration "${integrationId}" is required. Visit the connect URL to authorize.`,
149
+ "kontext_integration_connection_required",
150
+ { statusCode: 403, ...options }
151
+ );
152
+ this.name = "IntegrationConnectionRequiredError";
153
+ this.integrationId = integrationId;
154
+ this.integrationName = options?.integrationName;
155
+ this.connectUrl = options?.connectUrl;
156
+ }
157
+ };
158
+ var ConfigError = class extends KontextError {
159
+ constructor(message, code, options) {
160
+ super(message, code, options);
161
+ this.name = "ConfigError";
162
+ }
163
+ };
164
+ var NetworkError = class extends KontextError {
165
+ constructor(message = "Network error. Check your internet connection and that the server is reachable.", options) {
166
+ super(message, "kontext_network_error", options);
167
+ this.name = "NetworkError";
168
+ }
169
+ };
170
+ function errorProps(err) {
171
+ return err;
172
+ }
173
+ var NETWORK_ERROR_CODES = /* @__PURE__ */ new Set([
174
+ "ECONNREFUSED",
175
+ "ENOTFOUND",
176
+ "ETIMEDOUT",
177
+ "ECONNRESET",
178
+ "ECONNABORTED",
179
+ "EPIPE",
180
+ "UND_ERR_CONNECT_TIMEOUT"
181
+ ]);
182
+ function isNetworkError(err) {
183
+ if (err.name === "AbortError") return true;
184
+ const props = errorProps(err);
185
+ const sysCode = props.code;
186
+ if (typeof sysCode === "string" && NETWORK_ERROR_CODES.has(sysCode))
187
+ return true;
188
+ if (err.name === "TypeError" && err.cause instanceof Error) {
189
+ const causeCode = errorProps(err.cause).code;
190
+ if (typeof causeCode === "string" && NETWORK_ERROR_CODES.has(causeCode))
191
+ return true;
192
+ }
193
+ return false;
194
+ }
195
+ function isUnauthorizedError(err) {
196
+ const props = errorProps(err);
197
+ if (props.statusCode === 401 || props.status === 401) return true;
198
+ if (err.name === "UnauthorizedError") return true;
199
+ if (err.message === "Unauthorized") return true;
200
+ return false;
201
+ }
202
+
203
+ // src/oauth/provider.ts
204
+ var KontextOAuthProvider = class {
205
+ config;
206
+ storagePrefix;
207
+ pendingState = null;
208
+ expiryBufferMs = 60 * 1e3;
209
+ constructor(config) {
210
+ this.config = config;
211
+ this.storagePrefix = createStorageKey(config.clientId, config.sessionKey);
212
+ }
213
+ /**
214
+ * The redirect URL for OAuth callbacks
215
+ */
216
+ get redirectUrl() {
217
+ return this.config.redirectUri;
218
+ }
219
+ /**
220
+ * OAuth client metadata
221
+ */
222
+ get clientMetadata() {
223
+ return {
224
+ redirect_uris: [this.config.redirectUri],
225
+ client_name: this.config.clientName,
226
+ grant_types: ["authorization_code", "refresh_token"],
227
+ response_types: ["code"],
228
+ token_endpoint_auth_method: "none"
229
+ // Public client
230
+ };
231
+ }
232
+ /**
233
+ * Generate a random state parameter for OAuth CSRF protection
234
+ */
235
+ state() {
236
+ const array = new Uint8Array(32);
237
+ if (globalThis.crypto?.getRandomValues) {
238
+ globalThis.crypto.getRandomValues(array);
239
+ } else {
240
+ array.set(crypto.randomBytes(32));
241
+ }
242
+ const state = Array.from(
243
+ array,
244
+ (byte) => byte.toString(16).padStart(2, "0")
245
+ ).join("");
246
+ this.pendingState = state;
247
+ void this.config.storage.setJson(
248
+ this.getStorageKey(StorageKeys.STATE),
249
+ state
250
+ );
251
+ return state;
252
+ }
253
+ /**
254
+ * Returns the client information (client_id)
255
+ * Since we're a public client with pre-registered credentials,
256
+ * we don't use dynamic client registration.
257
+ */
258
+ async clientInformation() {
259
+ return {
260
+ client_id: this.config.clientId
261
+ };
262
+ }
263
+ /**
264
+ * Load stored OAuth tokens
265
+ */
266
+ async tokens() {
267
+ const key = this.getStorageKey(StorageKeys.TOKENS);
268
+ return this.config.storage.getJson(key);
269
+ }
270
+ /**
271
+ * Save OAuth tokens after successful authorization
272
+ */
273
+ async saveTokens(tokens) {
274
+ const key = this.getStorageKey(StorageKeys.TOKENS);
275
+ await this.config.storage.setJson(key, this.withIssuedAt(tokens));
276
+ }
277
+ /**
278
+ * Redirect the user agent to the authorization URL
279
+ */
280
+ async redirectToAuthorization(authorizationUrl) {
281
+ await this.config.onRedirectToAuthorization(authorizationUrl);
282
+ }
283
+ /**
284
+ * Save the PKCE code verifier before redirecting to authorization
285
+ */
286
+ async saveCodeVerifier(codeVerifier) {
287
+ const key = this.getStorageKey(StorageKeys.CODE_VERIFIER);
288
+ await this.config.storage.setJson(key, codeVerifier);
289
+ }
290
+ /**
291
+ * Load the PKCE code verifier for token exchange
292
+ */
293
+ async codeVerifier() {
294
+ const key = this.getStorageKey(StorageKeys.CODE_VERIFIER);
295
+ const verifier = await this.config.storage.getJson(key);
296
+ if (!verifier) {
297
+ throw new OAuthError(
298
+ "No PKCE code verifier found in storage. The OAuth flow may have expired or storage was cleared. Restart the auth flow.",
299
+ "kontext_oauth_code_verifier_missing"
300
+ );
301
+ }
302
+ return verifier;
303
+ }
304
+ /**
305
+ * Invalidate stored credentials
306
+ */
307
+ async invalidateCredentials(scope) {
308
+ if (scope === "all" || scope === "tokens") {
309
+ const tokensKey = this.getStorageKey(StorageKeys.TOKENS);
310
+ await this.config.storage.setJson(tokensKey, void 0);
311
+ const identityKey = this.getStorageKey(StorageKeys.IDENTITY_TOKENS);
312
+ await this.config.storage.setJson(identityKey, void 0);
313
+ }
314
+ if (scope === "all" || scope === "verifier") {
315
+ const verifierKey = this.getStorageKey(StorageKeys.CODE_VERIFIER);
316
+ await this.config.storage.setJson(verifierKey, void 0);
317
+ }
318
+ if (scope === "all") {
319
+ this.pendingState = null;
320
+ const stateKey = this.getStorageKey(StorageKeys.STATE);
321
+ await this.config.storage.setJson(stateKey, void 0);
322
+ }
323
+ }
324
+ /**
325
+ * Clear all stored state (tokens, verifier, etc.)
326
+ * Call this to force re-authentication
327
+ */
328
+ async clearAll() {
329
+ await this.invalidateCredentials("all");
330
+ }
331
+ /**
332
+ * Check if we have valid (non-expired) tokens
333
+ */
334
+ async hasValidTokens() {
335
+ const storedTokens = await this.tokens();
336
+ return this.isTokenValid(storedTokens);
337
+ }
338
+ // ==========================================================================
339
+ // Pattern B: Identity and Resource Token Management (RFC 8693)
340
+ // ==========================================================================
341
+ /**
342
+ * Save identity tokens (no audience)
343
+ * These are the tokens obtained from the initial OAuth flow before token exchange.
344
+ */
345
+ async saveIdentityTokens(tokens) {
346
+ const key = this.getStorageKey(StorageKeys.IDENTITY_TOKENS);
347
+ await this.config.storage.setJson(key, this.withIssuedAt(tokens));
348
+ }
349
+ /**
350
+ * Load identity tokens
351
+ * Returns the identity tokens obtained from the initial OAuth flow.
352
+ */
353
+ async identityTokens() {
354
+ const key = this.getStorageKey(StorageKeys.IDENTITY_TOKENS);
355
+ return this.config.storage.getJson(key);
356
+ }
357
+ /**
358
+ * Save resource-scoped tokens for a specific resource
359
+ *
360
+ * @param resource The resource identifier (e.g., "mcp-gateway")
361
+ * @param tokens The resource-scoped tokens
362
+ */
363
+ async saveResourceTokens(resource, tokens) {
364
+ const key = this.getStorageKey(resourceTokenKey(resource));
365
+ await this.config.storage.setJson(key, this.withIssuedAt(tokens));
366
+ }
367
+ /**
368
+ * Load resource-scoped tokens for a specific resource
369
+ *
370
+ * @param resource The resource identifier (e.g., "mcp-gateway")
371
+ * @returns The resource-scoped tokens, or undefined if not found
372
+ */
373
+ async resourceTokens(resource) {
374
+ const key = this.getStorageKey(resourceTokenKey(resource));
375
+ return this.config.storage.getJson(key);
376
+ }
377
+ /**
378
+ * Clear resource tokens for a specific resource
379
+ *
380
+ * @param resource The resource identifier (e.g., "mcp-gateway")
381
+ */
382
+ async clearResourceTokens(resource) {
383
+ const key = this.getStorageKey(resourceTokenKey(resource));
384
+ await this.config.storage.setJson(key, void 0);
385
+ }
386
+ /**
387
+ * Check if we have valid identity tokens
388
+ */
389
+ async hasValidIdentityTokens() {
390
+ const tokens = await this.identityTokens();
391
+ return this.isTokenValid(tokens);
392
+ }
393
+ /**
394
+ * Check if we have valid resource tokens for a specific resource
395
+ *
396
+ * @param resource The resource identifier
397
+ */
398
+ async hasValidResourceTokens(resource) {
399
+ const tokens = await this.resourceTokens(resource);
400
+ return this.isTokenValid(tokens);
401
+ }
402
+ async validateState(state) {
403
+ if (!state) {
404
+ return false;
405
+ }
406
+ const key = this.getStorageKey(StorageKeys.STATE);
407
+ const storedState = this.pendingState ?? await this.config.storage.getJson(key);
408
+ const isValid = storedState === state;
409
+ if (isValid) {
410
+ this.pendingState = null;
411
+ await this.config.storage.setJson(key, void 0);
412
+ }
413
+ return isValid;
414
+ }
415
+ withIssuedAt(tokens) {
416
+ if (!tokens.expires_in) {
417
+ return tokens;
418
+ }
419
+ return { ...tokens, issued_at: Date.now() };
420
+ }
421
+ isTokenValid(tokens) {
422
+ if (!tokens?.access_token) {
423
+ return false;
424
+ }
425
+ if (!tokens.expires_in) {
426
+ return true;
427
+ }
428
+ const issuedAt = tokens.issued_at;
429
+ if (!issuedAt) {
430
+ return true;
431
+ }
432
+ const expiresAt = issuedAt + tokens.expires_in * 1e3;
433
+ return Date.now() < expiresAt - this.expiryBufferMs;
434
+ }
435
+ getStorageKey(key) {
436
+ return `${this.storagePrefix}:${key}`;
437
+ }
438
+ };
439
+ function parseOAuthCallback(callbackUrl) {
440
+ const url = typeof callbackUrl === "string" ? new URL(callbackUrl) : callbackUrl;
441
+ const params = url.searchParams;
442
+ const error = params.get("error");
443
+ if (error) {
444
+ return {
445
+ error,
446
+ errorDescription: params.get("error_description") ?? void 0
447
+ };
448
+ }
449
+ return {
450
+ code: params.get("code") ?? void 0,
451
+ state: params.get("state") ?? void 0
452
+ };
453
+ }
454
+
455
+ // src/mcp/client.ts
456
+ var DEFAULT_SERVER = "https://api.kontext.dev";
457
+ function normalizeKontextServerUrl(server) {
458
+ let url = server.replace(/\/$/, "");
459
+ url = url.replace(/\/api\/v1\/?$/, "").replace(/\/mcp\/?$/, "");
460
+ url = url.replace(/\/$/, "");
461
+ return url;
462
+ }
463
+ var KontextMcp = class {
464
+ config;
465
+ storage;
466
+ oauthProvider;
467
+ transport = null;
468
+ client = null;
469
+ _isConnected = false;
470
+ _pendingConnect = null;
471
+ _pendingAuthFlow = null;
472
+ _authFlowResolve = null;
473
+ constructor(config) {
474
+ this.config = config;
475
+ this.storage = config.storage ?? new MemoryStorage();
476
+ this.oauthProvider = new KontextOAuthProvider({
477
+ clientId: config.clientId,
478
+ redirectUri: config.redirectUri,
479
+ storage: this.storage,
480
+ sessionKey: config.sessionKey ?? "default",
481
+ clientName: config.clientName,
482
+ onRedirectToAuthorization: async (url) => {
483
+ this._pendingAuthFlow = new Promise((resolve) => {
484
+ this._authFlowResolve = resolve;
485
+ });
486
+ const result = await config.onAuthRequired(url);
487
+ if (result) {
488
+ await this.handleCallback(result);
489
+ }
490
+ }
491
+ });
492
+ }
493
+ /**
494
+ * Check if we're currently connected
495
+ */
496
+ get isConnected() {
497
+ return this._isConnected;
498
+ }
499
+ /**
500
+ * Get the underlying MCP client for advanced usage
501
+ */
502
+ get mcpClient() {
503
+ return this.client;
504
+ }
505
+ /**
506
+ * Get the session ID from the transport
507
+ */
508
+ get sessionId() {
509
+ return this.transport?.sessionId;
510
+ }
511
+ /**
512
+ * Get the server base URL
513
+ */
514
+ get serverUrl() {
515
+ return normalizeKontextServerUrl(this.config.server ?? DEFAULT_SERVER);
516
+ }
517
+ /**
518
+ * Get the MCP endpoint URL.
519
+ * When `url` is provided, use it directly. Otherwise derive from server.
520
+ */
521
+ get mcpEndpointUrl() {
522
+ return this.config.url ?? `${this.serverUrl}/mcp`;
523
+ }
524
+ /**
525
+ * List available tools from the server
526
+ *
527
+ * This will automatically handle authentication if needed.
528
+ */
529
+ async listTools() {
530
+ await this.ensureConnected();
531
+ const response = await this.client.listTools();
532
+ return response.tools;
533
+ }
534
+ /**
535
+ * Call a tool
536
+ *
537
+ * This will automatically handle authentication if needed.
538
+ *
539
+ * @param name The tool name
540
+ * @param args The tool arguments
541
+ */
542
+ async callTool(name, args) {
543
+ await this.ensureConnected();
544
+ try {
545
+ const result = await this.client.callTool({
546
+ name,
547
+ arguments: args
548
+ });
549
+ return result;
550
+ } catch (error) {
551
+ if (error instanceof types_js.UrlElicitationRequiredError && this.config.onElicitationUrl) {
552
+ for (const elicitation of error.elicitations) {
553
+ await this.config.onElicitationUrl({
554
+ url: elicitation.url,
555
+ message: elicitation.message ?? "Action required",
556
+ elicitationId: elicitation.elicitationId ?? "",
557
+ integrationId: elicitation.integrationId,
558
+ integrationName: elicitation.integrationName
559
+ });
560
+ }
561
+ }
562
+ throw error;
563
+ }
564
+ }
565
+ /**
566
+ * Create a connect session for the hosted connect UI.
567
+ *
568
+ * Returns a URL that can be opened in a browser to let the user
569
+ * connect integrations proactively (before hitting -32042 errors).
570
+ */
571
+ async createConnectSession() {
572
+ const tokens = await this.oauthProvider.tokens();
573
+ if (!tokens?.access_token) {
574
+ throw new AuthorizationRequiredError(
575
+ "Authorization required. Complete the OAuth flow first."
576
+ );
577
+ }
578
+ const response = await fetch(`${this.serverUrl}/mcp/connect-session`, {
579
+ method: "POST",
580
+ headers: {
581
+ Authorization: `Bearer ${tokens.access_token}`,
582
+ "Content-Type": "application/json"
583
+ }
584
+ });
585
+ if (response.status === 401) {
586
+ throw new AuthorizationRequiredError(
587
+ "Access token expired or invalid. Re-authenticate and retry."
588
+ );
589
+ }
590
+ if (!response.ok) {
591
+ throw new KontextError(
592
+ `Failed to create connect session: HTTP ${response.status}`,
593
+ "kontext_connect_session_failed",
594
+ { statusCode: response.status }
595
+ );
596
+ }
597
+ return await response.json();
598
+ }
599
+ /**
600
+ * List integrations attached to the current application/runtime identity.
601
+ *
602
+ * This is used by higher-level orchestrators to discover mixed integration
603
+ * topologies (gateway + internal credential integrations).
604
+ */
605
+ async listRuntimeIntegrations() {
606
+ const tokens = await this.oauthProvider.tokens();
607
+ if (!tokens?.access_token) {
608
+ throw new AuthorizationRequiredError(
609
+ "Authorization required. Complete the OAuth flow first."
610
+ );
611
+ }
612
+ const response = await fetch(`${this.serverUrl}/mcp/integrations`, {
613
+ method: "GET",
614
+ headers: {
615
+ Authorization: `Bearer ${tokens.access_token}`
616
+ }
617
+ });
618
+ if (response.status === 401) {
619
+ throw new AuthorizationRequiredError(
620
+ "Access token expired or invalid. Re-authenticate and retry."
621
+ );
622
+ }
623
+ if (!response.ok) {
624
+ throw new KontextError(
625
+ `Failed to list runtime integrations: HTTP ${response.status}`,
626
+ "kontext_runtime_integrations_failed",
627
+ { statusCode: response.status }
628
+ );
629
+ }
630
+ const payload = await response.json();
631
+ const items = Array.isArray(payload?.items) ? payload.items : [];
632
+ return items.map((item) => {
633
+ const id = typeof item.id === "string" ? item.id : "";
634
+ const name = typeof item.name === "string" ? item.name : id;
635
+ const url = typeof item.url === "string" ? item.url : "";
636
+ if (!id || !url) return null;
637
+ const category = item.category === "internal_mcp_credentials" ? "internal_mcp_credentials" : "gateway_remote_mcp";
638
+ const connectType = item.connectType === "credentials" || item.connectType === "oauth" || item.connectType === "none" ? item.connectType : category === "internal_mcp_credentials" ? "credentials" : item.authMode === "oauth" ? "oauth" : "none";
639
+ const rawConnection = item.connection && typeof item.connection === "object" ? item.connection : void 0;
640
+ const connected = rawConnection && typeof rawConnection.connected === "boolean" ? rawConnection.connected : false;
641
+ const status = rawConnection?.status === "connected" ? "connected" : "disconnected";
642
+ return {
643
+ id,
644
+ name,
645
+ url,
646
+ category,
647
+ connectType,
648
+ authMode: item.authMode === "oauth" || item.authMode === "user_token" || item.authMode === "server_token" || item.authMode === "none" ? item.authMode : void 0,
649
+ credentialSchema: item.credentialSchema,
650
+ requiresOauth: typeof item.requiresOauth === "boolean" ? item.requiresOauth : void 0,
651
+ connection: rawConnection ? {
652
+ connected,
653
+ status,
654
+ expiresAt: typeof rawConnection.expiresAt === "string" ? rawConnection.expiresAt : void 0,
655
+ displayName: typeof rawConnection.displayName === "string" ? rawConnection.displayName : void 0
656
+ } : void 0
657
+ };
658
+ }).filter((item) => item !== null);
659
+ }
660
+ /**
661
+ * Handle an OAuth callback URL
662
+ *
663
+ * Call this after the user has been redirected back from authorization.
664
+ * This is required for web apps where `onAuthRequired` redirects instead of waiting.
665
+ *
666
+ * @param callbackUrl The full callback URL with query parameters
667
+ */
668
+ async handleCallback(callbackUrl) {
669
+ const { code, state, error, errorDescription } = parseOAuthCallback(callbackUrl);
670
+ if (error) {
671
+ this._authFlowResolve?.();
672
+ this._authFlowResolve = null;
673
+ throw new AuthorizationRequiredError(
674
+ errorDescription ?? `OAuth error: ${error}`
675
+ );
676
+ }
677
+ const isValidState = await this.oauthProvider.validateState(state);
678
+ if (!isValidState) {
679
+ this._authFlowResolve?.();
680
+ this._authFlowResolve = null;
681
+ throw new OAuthError(
682
+ "OAuth state validation failed. The state parameter did not match. Retry the authorization flow.",
683
+ "kontext_oauth_state_invalid"
684
+ );
685
+ }
686
+ if (!code) {
687
+ this._authFlowResolve?.();
688
+ this._authFlowResolve = null;
689
+ throw new AuthorizationRequiredError(
690
+ "No authorization code in callback URL"
691
+ );
692
+ }
693
+ try {
694
+ if (!this.transport) {
695
+ this.transport = new streamableHttp_js.StreamableHTTPClientTransport(
696
+ new URL(this.mcpEndpointUrl),
697
+ {
698
+ authProvider: this.oauthProvider
699
+ }
700
+ );
701
+ }
702
+ await this.transport.finishAuth(code);
703
+ const tokens = await this.oauthProvider.tokens();
704
+ if (!tokens?.access_token) {
705
+ throw new AuthorizationRequiredError("Failed to obtain tokens");
706
+ }
707
+ await this.oauthProvider.saveTokens(tokens);
708
+ } finally {
709
+ this._authFlowResolve?.();
710
+ this._authFlowResolve = null;
711
+ }
712
+ }
713
+ /**
714
+ * Disconnect from the server
715
+ */
716
+ async disconnect() {
717
+ try {
718
+ if (this.transport) {
719
+ try {
720
+ await this.transport.terminateSession();
721
+ } catch {
722
+ }
723
+ await this.transport.close();
724
+ }
725
+ } finally {
726
+ this.transport = null;
727
+ this.client = null;
728
+ this._isConnected = false;
729
+ }
730
+ }
731
+ /**
732
+ * Clear stored tokens and require re-authentication
733
+ */
734
+ async clearAuth() {
735
+ await this.oauthProvider.clearAll();
736
+ await this.disconnect();
737
+ }
738
+ /**
739
+ * Check if this URL is an OAuth callback
740
+ *
741
+ * Useful for web apps to detect if the current URL is a callback.
742
+ *
743
+ * @param url The URL to check
744
+ */
745
+ isCallback(url) {
746
+ const urlObj = typeof url === "string" ? new URL(url) : url;
747
+ const redirectUri = new URL(this.config.redirectUri);
748
+ return urlObj.pathname === redirectUri.pathname && (urlObj.searchParams.has("code") || urlObj.searchParams.has("error"));
749
+ }
750
+ /**
751
+ * Ensure we're connected, handling auth if needed
752
+ */
753
+ async ensureConnected() {
754
+ if (this._isConnected && this.client) {
755
+ return;
756
+ }
757
+ if (this._pendingConnect) {
758
+ await this._pendingConnect;
759
+ return;
760
+ }
761
+ this._pendingConnect = this.doConnect();
762
+ try {
763
+ await this._pendingConnect;
764
+ } finally {
765
+ this._pendingConnect = null;
766
+ }
767
+ }
768
+ /**
769
+ * Internal connection logic
770
+ */
771
+ async doConnect(authRetryCount = 0) {
772
+ if (!this.transport) {
773
+ this.transport = new streamableHttp_js.StreamableHTTPClientTransport(
774
+ new URL(this.mcpEndpointUrl),
775
+ {
776
+ authProvider: this.oauthProvider
777
+ }
778
+ );
779
+ }
780
+ const capabilities = {
781
+ tools: {}
782
+ };
783
+ if (this.config.onElicitationUrl) {
784
+ capabilities.elicitation = { url: {} };
785
+ }
786
+ this.client = new index_js.Client(
787
+ {
788
+ name: this.config.clientName ?? "kontext-sdk",
789
+ version: this.config.clientVersion ?? "0.0.1"
790
+ },
791
+ { capabilities }
792
+ );
793
+ if (this.config.onElicitationUrl) {
794
+ const onElicitationUrl = this.config.onElicitationUrl;
795
+ this.client.setRequestHandler(types_js.ElicitRequestSchema, async (request) => {
796
+ const params = request.params;
797
+ if (params.mode === "url" && "url" in params) {
798
+ await onElicitationUrl({
799
+ url: params.url,
800
+ message: params.message ?? "Action required",
801
+ elicitationId: params.elicitationId ?? "",
802
+ integrationId: params.integrationId,
803
+ integrationName: params.integrationName
804
+ });
805
+ }
806
+ return { action: "accept" };
807
+ });
808
+ this.client.setNotificationHandler(
809
+ types_js.ElicitationCompleteNotificationSchema,
810
+ () => {
811
+ }
812
+ );
813
+ }
814
+ try {
815
+ await this.client.connect(this.transport);
816
+ this._isConnected = true;
817
+ } catch (error) {
818
+ if (error instanceof Error && isUnauthorizedError(error)) {
819
+ if (this._pendingAuthFlow) {
820
+ await this._pendingAuthFlow;
821
+ this._pendingAuthFlow = null;
822
+ this.transport = null;
823
+ this.client = null;
824
+ if (authRetryCount >= 1) {
825
+ throw new AuthorizationRequiredError(
826
+ "Authorization completed, but the MCP server still rejected the token. Verify OAuth resource audience and token issuer configuration.",
827
+ { cause: error }
828
+ );
829
+ }
830
+ return this.doConnect(authRetryCount + 1);
831
+ }
832
+ this.transport = null;
833
+ this.client = null;
834
+ throw new AuthorizationRequiredError(
835
+ "Authorization required. Complete the OAuth flow and retry."
836
+ );
837
+ }
838
+ this.transport = null;
839
+ this.client = null;
840
+ if (error instanceof KontextError) throw error;
841
+ throw new KontextError(
842
+ `Failed to connect to MCP server at ${this.mcpEndpointUrl}. ${error instanceof Error ? error.message : String(error)}`,
843
+ "kontext_mcp_connection_failed",
844
+ { cause: error }
845
+ );
846
+ }
847
+ }
848
+ };
849
+
850
+ // src/client/tool-utils.ts
851
+ function parseIntegrationStatus(tools, errors, elicitations) {
852
+ const seen = /* @__PURE__ */ new Set();
853
+ const result = [];
854
+ for (const t of tools) {
855
+ const sid = t.server?.id;
856
+ if (sid && !seen.has(sid)) {
857
+ seen.add(sid);
858
+ result.push({
859
+ id: sid,
860
+ name: t.server?.name ?? sid,
861
+ connected: true
862
+ });
863
+ }
864
+ }
865
+ for (const e of errors) {
866
+ if (!seen.has(e.serverId)) {
867
+ seen.add(e.serverId);
868
+ const elicitation = elicitations?.find(
869
+ (el) => el.integrationId === e.serverId
870
+ );
871
+ result.push({
872
+ id: e.serverId,
873
+ name: e.serverName ?? e.serverId,
874
+ connected: false,
875
+ connectUrl: elicitation?.url
876
+ });
877
+ }
878
+ }
879
+ return result;
880
+ }
881
+
882
+ // src/client/orchestrator/internal/backends.ts
883
+ function gatewayBackendId() {
884
+ return "gateway";
885
+ }
886
+ function internalBackendId(integrationId) {
887
+ return `internal:${integrationId}`;
888
+ }
889
+ function isInternalIntegration(integration) {
890
+ return integration.category === "internal_mcp_credentials";
891
+ }
892
+ function sortInternalIntegrations(integrations) {
893
+ return integrations.filter(isInternalIntegration).sort((a, b) => a.id.localeCompare(b.id));
894
+ }
895
+ function createGatewayBackend(client) {
896
+ return {
897
+ backendId: gatewayBackendId(),
898
+ source: "gateway",
899
+ client
900
+ };
901
+ }
902
+ function createInternalBackend(input) {
903
+ return {
904
+ backendId: internalBackendId(input.integration.id),
905
+ source: "internal",
906
+ client: input.client,
907
+ integrationId: input.integration.id,
908
+ integrationName: input.integration.name
909
+ };
910
+ }
911
+
912
+ // src/client/orchestrator/internal/routes.ts
913
+ function emptyRouteInventorySnapshot() {
914
+ return {
915
+ version: 0,
916
+ tools: [],
917
+ routes: /* @__PURE__ */ new Map(),
918
+ conflicts: []
919
+ };
920
+ }
921
+ function buildRouteInventory(version, candidates, options) {
922
+ const tools = [];
923
+ const routes = /* @__PURE__ */ new Map();
924
+ const conflicts = [];
925
+ for (const candidate of candidates) {
926
+ const toolId = candidate.route.toolId;
927
+ if (!routes.has(toolId)) {
928
+ routes.set(toolId, candidate.route);
929
+ tools.push(candidate.tool);
930
+ continue;
931
+ }
932
+ const existing = routes.get(toolId);
933
+ const decision = options?.onConflict?.(existing, candidate.route) ?? "keep_existing";
934
+ let kept = existing;
935
+ let dropped = candidate.route;
936
+ if (decision === "replace_existing") {
937
+ const existingIdx = tools.findIndex((tool) => tool.id === toolId);
938
+ if (existingIdx >= 0) {
939
+ tools.splice(existingIdx, 1, candidate.tool);
940
+ } else {
941
+ tools.push(candidate.tool);
942
+ }
943
+ routes.set(toolId, candidate.route);
944
+ kept = candidate.route;
945
+ dropped = existing;
946
+ }
947
+ conflicts.push({
948
+ toolId,
949
+ kept,
950
+ dropped
951
+ });
952
+ }
953
+ return {
954
+ version,
955
+ tools,
956
+ routes,
957
+ conflicts
958
+ };
959
+ }
960
+
961
+ // src/client/orchestrator/internal/inventory.ts
962
+ var RouteInventoryStore = class {
963
+ versionCounter = 0;
964
+ resetGeneration = 0;
965
+ buildRunCounter = 0;
966
+ latestCommittedBuildRun = 0;
967
+ snapshotState = emptyRouteInventorySnapshot();
968
+ pendingBuilds = /* @__PURE__ */ new Map();
969
+ get version() {
970
+ return this.snapshotState.version;
971
+ }
972
+ get snapshot() {
973
+ return this.snapshotState;
974
+ }
975
+ routeFor(toolId) {
976
+ return this.snapshotState.routes.get(toolId);
977
+ }
978
+ async build(buildCandidates, options) {
979
+ const key = options?.key ?? "__default__";
980
+ const existingBuild = this.pendingBuilds.get(key);
981
+ if (existingBuild) {
982
+ return await existingBuild;
983
+ }
984
+ const buildGeneration = this.resetGeneration;
985
+ const buildRun = ++this.buildRunCounter;
986
+ const pendingPromise = (async () => {
987
+ const candidates = await buildCandidates();
988
+ if (this.resetGeneration !== buildGeneration) {
989
+ return this.snapshotState;
990
+ }
991
+ if (buildRun >= this.latestCommittedBuildRun) {
992
+ this.latestCommittedBuildRun = buildRun;
993
+ this.versionCounter += 1;
994
+ const snapshot = buildRouteInventory(this.versionCounter, candidates, {
995
+ onConflict: options?.onConflict
996
+ });
997
+ this.snapshotState = snapshot;
998
+ return snapshot;
999
+ }
1000
+ return buildRouteInventory(this.snapshotState.version, candidates, {
1001
+ onConflict: options?.onConflict
1002
+ });
1003
+ })();
1004
+ this.pendingBuilds.set(key, pendingPromise);
1005
+ try {
1006
+ return await pendingPromise;
1007
+ } finally {
1008
+ if (this.pendingBuilds.get(key) === pendingPromise) {
1009
+ this.pendingBuilds.delete(key);
1010
+ }
1011
+ }
1012
+ }
1013
+ reset() {
1014
+ this.resetGeneration += 1;
1015
+ this.versionCounter = 0;
1016
+ this.latestCommittedBuildRun = this.buildRunCounter;
1017
+ this.snapshotState = emptyRouteInventorySnapshot();
1018
+ this.pendingBuilds.clear();
1019
+ }
1020
+ };
1021
+
1022
+ // src/client/orchestrator/internal/policy.ts
1023
+ var defaultRoutingPolicy = {
1024
+ onRouteConflict() {
1025
+ return "keep_existing";
1026
+ }
1027
+ };
1028
+ function toRouteConflictError(input) {
1029
+ return new KontextError(
1030
+ `Route conflict for tool "${input.toolId}". Keeping backend "${input.kept.backendId}" and dropping "${input.dropped.backendId}".`,
1031
+ "kontext_tool_route_conflict",
1032
+ {
1033
+ meta: {
1034
+ toolId: input.toolId,
1035
+ keptBackendId: input.kept.backendId,
1036
+ keptSource: input.kept.source,
1037
+ keptIntegrationId: input.kept.integrationId,
1038
+ droppedBackendId: input.dropped.backendId,
1039
+ droppedSource: input.dropped.source,
1040
+ droppedIntegrationId: input.dropped.integrationId
1041
+ }
1042
+ }
1043
+ );
1044
+ }
1045
+
1046
+ // src/client/orchestrator/internal/state.ts
1047
+ function createOrchestratorStateController(input) {
1048
+ let state = input.initialState ?? "idle";
1049
+ const listeners = /* @__PURE__ */ new Map();
1050
+ function setState(next) {
1051
+ if (state === next) return;
1052
+ state = next;
1053
+ try {
1054
+ input.onStateChange?.(next);
1055
+ } catch {
1056
+ }
1057
+ const handlers = listeners.get("stateChange");
1058
+ if (!handlers) return;
1059
+ for (const handler of handlers) {
1060
+ try {
1061
+ handler(next);
1062
+ } catch {
1063
+ }
1064
+ }
1065
+ }
1066
+ function emitError(error) {
1067
+ const handlers = listeners.get("error");
1068
+ if (!handlers) return;
1069
+ for (const handler of handlers) {
1070
+ try {
1071
+ handler(error);
1072
+ } catch {
1073
+ }
1074
+ }
1075
+ }
1076
+ function on(event, handler) {
1077
+ if (!listeners.has(event)) {
1078
+ listeners.set(event, /* @__PURE__ */ new Set());
1079
+ }
1080
+ listeners.get(event).add(handler);
1081
+ return () => {
1082
+ listeners.get(event)?.delete(handler);
1083
+ };
1084
+ }
1085
+ return {
1086
+ get state() {
1087
+ return state;
1088
+ },
1089
+ setState,
1090
+ emitError,
1091
+ on
1092
+ };
1093
+ }
1094
+
1095
+ // src/client/orchestrator/token-manager.ts
1096
+ function hasFreshStoredToken(tokens, skewMs = 3e4) {
1097
+ if (!tokens?.access_token) return false;
1098
+ const expiresIn = typeof tokens.expires_in === "number" ? tokens.expires_in : Number(tokens.expires_in);
1099
+ const issuedAt = typeof tokens.issued_at === "number" ? tokens.issued_at : Number(tokens.issued_at);
1100
+ if (!Number.isFinite(expiresIn) || !Number.isFinite(issuedAt)) {
1101
+ return false;
1102
+ }
1103
+ const expiresAt = issuedAt + expiresIn * 1e3;
1104
+ return Date.now() + skewMs < expiresAt;
1105
+ }
1106
+ function createTokenManager(input) {
1107
+ const pendingInternalTokenExchange = /* @__PURE__ */ new Map();
1108
+ function tokenStorageKey(sessionKey) {
1109
+ return createStorageKey(input.clientId, sessionKey, StorageKeys.TOKENS);
1110
+ }
1111
+ async function readGatewayTokens() {
1112
+ const identityTokens = await input.storage.getJson(
1113
+ createStorageKey(
1114
+ input.clientId,
1115
+ input.gatewaySessionKey,
1116
+ StorageKeys.IDENTITY_TOKENS
1117
+ )
1118
+ );
1119
+ const gatewayTokens = await input.storage.getJson(tokenStorageKey(input.gatewaySessionKey));
1120
+ return {
1121
+ subjectToken: identityTokens?.access_token ?? gatewayTokens?.access_token ?? null
1122
+ };
1123
+ }
1124
+ async function ensureInternalResourceToken(integration, options) {
1125
+ const internalSessionKey = `${input.baseSessionKey}:internal:${integration.id}`;
1126
+ if (!options?.forceExchange) {
1127
+ const existingToken = await input.storage.getJson(
1128
+ tokenStorageKey(internalSessionKey)
1129
+ );
1130
+ if (hasFreshStoredToken(existingToken)) {
1131
+ return;
1132
+ }
1133
+ }
1134
+ const pending = pendingInternalTokenExchange.get(integration.id);
1135
+ if (pending) {
1136
+ return await pending;
1137
+ }
1138
+ const exchangePromise = (async () => {
1139
+ const { subjectToken: gatewaySubjectToken } = await readGatewayTokens();
1140
+ if (!gatewaySubjectToken) {
1141
+ return;
1142
+ }
1143
+ const body = new URLSearchParams({
1144
+ grant_type: "urn:ietf:params:oauth:grant-type:token-exchange",
1145
+ subject_token_type: "urn:ietf:params:oauth:token-type:access_token",
1146
+ subject_token: gatewaySubjectToken,
1147
+ resource: integration.url,
1148
+ client_id: input.clientId
1149
+ });
1150
+ const response = await fetch(`${input.serverUrl}/oauth2/token`, {
1151
+ method: "POST",
1152
+ headers: {
1153
+ "Content-Type": "application/x-www-form-urlencoded"
1154
+ },
1155
+ body: body.toString()
1156
+ });
1157
+ if (response.status === 401) {
1158
+ throw new AuthorizationRequiredError(
1159
+ "Access token expired or invalid. Re-authenticate and retry."
1160
+ );
1161
+ }
1162
+ if (!response.ok) {
1163
+ throw new KontextError(
1164
+ `Failed to exchange gateway token for internal resource "${integration.id}": HTTP ${response.status}`,
1165
+ "kontext_token_exchange_failed",
1166
+ {
1167
+ statusCode: response.status,
1168
+ meta: {
1169
+ integrationId: integration.id,
1170
+ resource: integration.url
1171
+ }
1172
+ }
1173
+ );
1174
+ }
1175
+ const exchanged = await response.json();
1176
+ if (!exchanged.access_token || !exchanged.token_type) {
1177
+ throw new KontextError(
1178
+ `Token exchange returned an invalid payload for integration "${integration.id}".`,
1179
+ "kontext_token_exchange_failed",
1180
+ {
1181
+ meta: {
1182
+ integrationId: integration.id,
1183
+ resource: integration.url
1184
+ }
1185
+ }
1186
+ );
1187
+ }
1188
+ await input.storage.setJson(tokenStorageKey(internalSessionKey), {
1189
+ ...exchanged,
1190
+ issued_at: Date.now()
1191
+ });
1192
+ })();
1193
+ pendingInternalTokenExchange.set(integration.id, exchangePromise);
1194
+ try {
1195
+ await exchangePromise;
1196
+ } finally {
1197
+ pendingInternalTokenExchange.delete(integration.id);
1198
+ }
1199
+ }
1200
+ return {
1201
+ tokenStorageKey,
1202
+ ensureInternalResourceToken
1203
+ };
1204
+ }
1205
+
1206
+ // src/client/orchestrator/internal-client-registry.ts
1207
+ function createInternalClientRegistry(input) {
1208
+ const internalClients = /* @__PURE__ */ new Map();
1209
+ async function remove(integrationId) {
1210
+ const existing = internalClients.get(integrationId);
1211
+ if (!existing) return;
1212
+ existing.unsubscribeState();
1213
+ existing.unsubscribeError();
1214
+ internalClients.delete(integrationId);
1215
+ input.backends.delete(existing.backendId);
1216
+ try {
1217
+ await existing.client.disconnect();
1218
+ } catch {
1219
+ }
1220
+ }
1221
+ async function sync(discovered) {
1222
+ const sortedInternal = sortInternalIntegrations(discovered);
1223
+ const desiredById = new Map(sortedInternal.map((item) => [item.id, item]));
1224
+ for (const [integrationId, existing] of internalClients) {
1225
+ const next = desiredById.get(integrationId);
1226
+ if (!next) {
1227
+ await remove(integrationId);
1228
+ continue;
1229
+ }
1230
+ if (existing.integration.url !== next.url) {
1231
+ await remove(integrationId);
1232
+ }
1233
+ }
1234
+ for (const integration of sortedInternal) {
1235
+ const existing = internalClients.get(integration.id);
1236
+ if (existing) {
1237
+ existing.integration = integration;
1238
+ const backend = input.backends.get(existing.backendId);
1239
+ if (backend) {
1240
+ backend.integrationName = integration.name;
1241
+ }
1242
+ continue;
1243
+ }
1244
+ const created = input.createClient(integration);
1245
+ input.backends.set(created.backend.backendId, created.backend);
1246
+ internalClients.set(integration.id, {
1247
+ integration,
1248
+ backendId: created.backend.backendId,
1249
+ client: created.client,
1250
+ unsubscribeState: created.unsubscribeState,
1251
+ unsubscribeError: created.unsubscribeError
1252
+ });
1253
+ }
1254
+ }
1255
+ function missingResolved(resolvedIntegrations) {
1256
+ const missing = [];
1257
+ for (const integrationId of internalClients.keys()) {
1258
+ if (!resolvedIntegrations.has(integrationId)) {
1259
+ missing.push(integrationId);
1260
+ }
1261
+ }
1262
+ return missing;
1263
+ }
1264
+ async function dispose(mode) {
1265
+ const entries = [...internalClients.values()];
1266
+ internalClients.clear();
1267
+ for (const backend of [...input.backends.values()]) {
1268
+ if (backend.source === "internal") {
1269
+ input.backends.delete(backend.backendId);
1270
+ }
1271
+ }
1272
+ await Promise.all(
1273
+ entries.map(async (entry) => {
1274
+ entry.unsubscribeState();
1275
+ entry.unsubscribeError();
1276
+ try {
1277
+ if (mode === "signOut") {
1278
+ await entry.client.auth.signOut();
1279
+ } else {
1280
+ await entry.client.disconnect();
1281
+ }
1282
+ } catch {
1283
+ }
1284
+ })
1285
+ );
1286
+ }
1287
+ return {
1288
+ get size() {
1289
+ return internalClients.size;
1290
+ },
1291
+ entries() {
1292
+ return internalClients.entries();
1293
+ },
1294
+ values() {
1295
+ return internalClients.values();
1296
+ },
1297
+ keys() {
1298
+ return internalClients.keys();
1299
+ },
1300
+ get(integrationId) {
1301
+ return internalClients.get(integrationId);
1302
+ },
1303
+ sync,
1304
+ missingResolved,
1305
+ dispose
1306
+ };
1307
+ }
1308
+
1309
+ // src/client/orchestrator/index.ts
1310
+ function isTransientError(err) {
1311
+ if (err instanceof Error && isNetworkError(err)) {
1312
+ return true;
1313
+ }
1314
+ if (isKontextError(err)) {
1315
+ if (err.code === "kontext_network_error") return true;
1316
+ if (err.statusCode === 429) return true;
1317
+ if (typeof err.statusCode === "number" && err.statusCode >= 500) {
1318
+ return true;
1319
+ }
1320
+ return false;
1321
+ }
1322
+ if (typeof err === "object" && err !== null) {
1323
+ const errObj = err;
1324
+ const maybeStatus = errObj.statusCode ?? errObj.status;
1325
+ const status = typeof maybeStatus === "number" ? maybeStatus : void 0;
1326
+ if (status === 429 || typeof status === "number" && status >= 500) {
1327
+ return true;
1328
+ }
1329
+ }
1330
+ return false;
1331
+ }
1332
+ async function withTransientRetry(operation, maxRetries = 1) {
1333
+ const retryDelayMs = 250;
1334
+ for (let attempt = 0; attempt <= maxRetries; attempt += 1) {
1335
+ try {
1336
+ return await operation();
1337
+ } catch (err) {
1338
+ if (attempt >= maxRetries || !isTransientError(err)) {
1339
+ throw err;
1340
+ }
1341
+ await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
1342
+ }
1343
+ }
1344
+ throw new Error("Transient retry loop exhausted unexpectedly.");
1345
+ }
1346
+ function toKontextError(err, context) {
1347
+ const contextMeta = context ? { ...context } : void 0;
1348
+ const mergeMeta = (base) => contextMeta ? { ...base ?? {}, ...contextMeta } : base ?? {};
1349
+ if (isKontextError(err)) {
1350
+ if (!contextMeta) {
1351
+ return err;
1352
+ }
1353
+ const cloned = Object.create(Object.getPrototypeOf(err));
1354
+ Object.defineProperties(cloned, Object.getOwnPropertyDescriptors(err));
1355
+ Object.defineProperty(cloned, "meta", {
1356
+ value: mergeMeta(err.meta),
1357
+ enumerable: true,
1358
+ writable: true,
1359
+ configurable: true
1360
+ });
1361
+ return cloned;
1362
+ }
1363
+ if (err instanceof Error) {
1364
+ if (isUnauthorizedError(err)) {
1365
+ return new AuthorizationRequiredError(err.message, {
1366
+ meta: mergeMeta(),
1367
+ cause: err
1368
+ });
1369
+ }
1370
+ return new KontextError(err.message, "kontext_unknown_error", {
1371
+ meta: mergeMeta(),
1372
+ cause: err
1373
+ });
1374
+ }
1375
+ return new KontextError(String(err), "kontext_unknown_error", {
1376
+ meta: mergeMeta()
1377
+ });
1378
+ }
1379
+ function isAuthorizationRequired(err) {
1380
+ if (err instanceof AuthorizationRequiredError) return true;
1381
+ if (isKontextError(err)) {
1382
+ return err.code === "kontext_authorization_required";
1383
+ }
1384
+ if (typeof err === "object" && err !== null) {
1385
+ return err.code === "kontext_authorization_required";
1386
+ }
1387
+ return false;
1388
+ }
1389
+ function isTokenExchangeFailure(err) {
1390
+ if (isKontextError(err)) {
1391
+ return err.code === "kontext_token_exchange_failed";
1392
+ }
1393
+ if (typeof err === "object" && err !== null) {
1394
+ return err.code === "kontext_token_exchange_failed";
1395
+ }
1396
+ return false;
1397
+ }
1398
+ function isAuthRecoveryRequired(err) {
1399
+ return isAuthorizationRequired(err) || isTokenExchangeFailure(err);
1400
+ }
1401
+ function createKontextOrchestrator(config) {
1402
+ if (!config.clientId) {
1403
+ throw new ConfigError(
1404
+ "clientId is required. Pass it in KontextOrchestratorConfig.",
1405
+ "kontext_config_missing_client_id"
1406
+ );
1407
+ }
1408
+ if (!config.redirectUri) {
1409
+ throw new ConfigError(
1410
+ "redirectUri is required. Set it to the URL where OAuth should redirect after authorization.",
1411
+ "kontext_config_missing_redirect_uri"
1412
+ );
1413
+ }
1414
+ if (!config.onAuthRequired) {
1415
+ throw new ConfigError(
1416
+ "onAuthRequired callback is required. Provide a function that opens the OAuth URL.",
1417
+ "kontext_config_missing_auth_handler"
1418
+ );
1419
+ }
1420
+ const baseSessionKey = config.sessionKey ?? "default";
1421
+ const serverUrl = normalizeKontextServerUrl(
1422
+ config.serverUrl ?? "https://api.kontext.dev"
1423
+ );
1424
+ const sharedStorage = config.storage ?? new MemoryStorage();
1425
+ const gatewaySessionKey = `${baseSessionKey}:gateway`;
1426
+ const authSourceQueue = [];
1427
+ const stateController = createOrchestratorStateController({
1428
+ initialState: "idle",
1429
+ onStateChange: config.onStateChange
1430
+ });
1431
+ const routeInventory = new RouteInventoryStore();
1432
+ const routingPolicy = defaultRoutingPolicy;
1433
+ const runtimeIntegrations = /* @__PURE__ */ new Map();
1434
+ const backends = /* @__PURE__ */ new Map();
1435
+ const managedInternalOps = /* @__PURE__ */ new Map();
1436
+ const resolvedInternalListings = /* @__PURE__ */ new Set();
1437
+ const tokenManager = createTokenManager({
1438
+ clientId: config.clientId,
1439
+ baseSessionKey,
1440
+ gatewaySessionKey,
1441
+ serverUrl,
1442
+ storage: sharedStorage
1443
+ });
1444
+ let pendingIntegrationRefresh = null;
1445
+ const gatewayClient = createSingleEndpointKontextClient({
1446
+ clientId: config.clientId,
1447
+ redirectUri: config.redirectUri,
1448
+ serverUrl: config.serverUrl,
1449
+ storage: sharedStorage,
1450
+ sessionKey: gatewaySessionKey,
1451
+ onAuthRequired: async (url) => {
1452
+ authSourceQueue.push("gateway");
1453
+ return await config.onAuthRequired(url);
1454
+ },
1455
+ onIntegrationRequired: config.onIntegrationRequired
1456
+ });
1457
+ const gatewayBackend = createGatewayBackend(gatewayClient);
1458
+ backends.set(gatewayBackendId(), gatewayBackend);
1459
+ gatewayClient.on("stateChange", (state) => {
1460
+ if (state === "needs_auth") {
1461
+ stateController.setState("needs_auth");
1462
+ }
1463
+ });
1464
+ gatewayClient.on("error", (error) => {
1465
+ const translated = toKontextError(error, {
1466
+ backendId: gatewayBackendId(),
1467
+ source: "gateway",
1468
+ operation: "client_error_event"
1469
+ });
1470
+ stateController.emitError(translated);
1471
+ if (isAuthRecoveryRequired(translated)) {
1472
+ stateController.setState("needs_auth");
1473
+ }
1474
+ });
1475
+ const ensureInternalResourceToken = tokenManager.ensureInternalResourceToken;
1476
+ function isInternalOpManaged(integrationId) {
1477
+ return (managedInternalOps.get(integrationId) ?? 0) > 0;
1478
+ }
1479
+ async function runManagedInternalOp(integrationId, operation) {
1480
+ managedInternalOps.set(
1481
+ integrationId,
1482
+ (managedInternalOps.get(integrationId) ?? 0) + 1
1483
+ );
1484
+ try {
1485
+ return await operation();
1486
+ } finally {
1487
+ const next = (managedInternalOps.get(integrationId) ?? 1) - 1;
1488
+ if (next <= 0) {
1489
+ managedInternalOps.delete(integrationId);
1490
+ } else {
1491
+ managedInternalOps.set(integrationId, next);
1492
+ }
1493
+ }
1494
+ }
1495
+ function createInternalClient(integration) {
1496
+ const client = createSingleEndpointKontextClient({
1497
+ clientId: config.clientId,
1498
+ redirectUri: config.redirectUri,
1499
+ url: integration.url,
1500
+ serverUrl: config.serverUrl,
1501
+ storage: sharedStorage,
1502
+ sessionKey: `${baseSessionKey}:internal:${integration.id}`,
1503
+ onAuthRequired: async (url) => {
1504
+ authSourceQueue.push(integration.id);
1505
+ return await config.onAuthRequired(url);
1506
+ },
1507
+ onIntegrationRequired: config.onIntegrationRequired
1508
+ });
1509
+ const unsubscribeState = client.on("stateChange", (state) => {
1510
+ if (state === "needs_auth") {
1511
+ stateController.setState("needs_auth");
1512
+ }
1513
+ });
1514
+ const unsubscribeError = client.on("error", (error) => {
1515
+ const translated = toKontextError(error, {
1516
+ backendId: internalBackendId(integration.id),
1517
+ source: "internal",
1518
+ integrationId: integration.id,
1519
+ operation: "client_error_event"
1520
+ });
1521
+ if (isInternalOpManaged(integration.id) && isAuthorizationRequired(translated)) {
1522
+ return;
1523
+ }
1524
+ if (isAuthRecoveryRequired(translated)) {
1525
+ stateController.setState("needs_auth");
1526
+ return;
1527
+ }
1528
+ stateController.emitError(translated);
1529
+ });
1530
+ const backend = createInternalBackend({ integration, client });
1531
+ return { backend, client, unsubscribeState, unsubscribeError };
1532
+ }
1533
+ const internalClientRegistry = createInternalClientRegistry({
1534
+ backends,
1535
+ createClient: createInternalClient
1536
+ });
1537
+ async function refreshIntegrationInventory(force = false) {
1538
+ if (pendingIntegrationRefresh) {
1539
+ if (!force) {
1540
+ return await pendingIntegrationRefresh;
1541
+ }
1542
+ await pendingIntegrationRefresh;
1543
+ }
1544
+ const refreshPromise = (async () => {
1545
+ const items = await withTransientRetry(
1546
+ async () => await gatewayClient.mcp.listRuntimeIntegrations()
1547
+ );
1548
+ await applyRuntimeIntegrations(items);
1549
+ return items;
1550
+ })();
1551
+ pendingIntegrationRefresh = refreshPromise;
1552
+ try {
1553
+ return await refreshPromise;
1554
+ } finally {
1555
+ if (pendingIntegrationRefresh === refreshPromise) {
1556
+ pendingIntegrationRefresh = null;
1557
+ }
1558
+ }
1559
+ }
1560
+ async function applyRuntimeIntegrations(integrations) {
1561
+ runtimeIntegrations.clear();
1562
+ for (const item of integrations) {
1563
+ runtimeIntegrations.set(item.id, item);
1564
+ }
1565
+ await internalClientRegistry.sync(integrations);
1566
+ }
1567
+ async function buildInventoryCandidates(options) {
1568
+ const candidates = [];
1569
+ resolvedInternalListings.clear();
1570
+ const pendingInternalAuthRetries = /* @__PURE__ */ new Set();
1571
+ const gatewayTools = await gatewayClient.tools.list(options);
1572
+ for (const tool of gatewayTools) {
1573
+ candidates.push({
1574
+ tool,
1575
+ route: {
1576
+ toolId: tool.id,
1577
+ backendId: gatewayBackendId(),
1578
+ source: "gateway",
1579
+ backendToolId: tool.id
1580
+ }
1581
+ });
1582
+ }
1583
+ if (options?.runtimeIntegrations) {
1584
+ await applyRuntimeIntegrations(options.runtimeIntegrations);
1585
+ } else {
1586
+ await refreshIntegrationInventory();
1587
+ }
1588
+ const sortedInternalEntries = [...internalClientRegistry.values()].sort(
1589
+ (a, b) => a.integration.id.localeCompare(b.integration.id)
1590
+ );
1591
+ const addInternalToolsForEntry = async (entry) => {
1592
+ const internalTools = await withTransientRetry(
1593
+ async () => await runManagedInternalOp(
1594
+ entry.integration.id,
1595
+ () => entry.client.tools.list()
1596
+ )
1597
+ );
1598
+ resolvedInternalListings.add(entry.integration.id);
1599
+ for (const tool of internalTools) {
1600
+ const backendToolId = tool.id || tool.name;
1601
+ const unifiedId = `${entry.integration.id}:${tool.name}`;
1602
+ candidates.push({
1603
+ tool: {
1604
+ id: unifiedId,
1605
+ name: tool.name,
1606
+ description: tool.description,
1607
+ inputSchema: tool.inputSchema,
1608
+ server: {
1609
+ id: entry.integration.id,
1610
+ name: entry.integration.name
1611
+ }
1612
+ },
1613
+ route: {
1614
+ toolId: unifiedId,
1615
+ backendId: entry.backendId,
1616
+ source: "internal",
1617
+ backendToolId,
1618
+ integrationId: entry.integration.id
1619
+ }
1620
+ });
1621
+ }
1622
+ };
1623
+ for (const entry of sortedInternalEntries) {
1624
+ try {
1625
+ await ensureInternalResourceToken(entry.integration);
1626
+ await addInternalToolsForEntry(entry);
1627
+ } catch (err) {
1628
+ const translated = toKontextError(err, {
1629
+ backendId: entry.backendId,
1630
+ source: "internal",
1631
+ integrationId: entry.integration.id,
1632
+ operation: "tools.list"
1633
+ });
1634
+ if (isAuthorizationRequired(translated)) {
1635
+ pendingInternalAuthRetries.add(entry.integration.id);
1636
+ continue;
1637
+ }
1638
+ if (isTokenExchangeFailure(translated)) {
1639
+ stateController.setState("needs_auth");
1640
+ }
1641
+ stateController.emitError(translated);
1642
+ }
1643
+ }
1644
+ if (pendingInternalAuthRetries.size > 0) {
1645
+ let hasUnresolvedAuth = false;
1646
+ for (const integrationId of pendingInternalAuthRetries) {
1647
+ const entry = internalClientRegistry.get(integrationId);
1648
+ if (!entry) continue;
1649
+ try {
1650
+ await ensureInternalResourceToken(entry.integration, {
1651
+ forceExchange: true
1652
+ });
1653
+ await runManagedInternalOp(integrationId, async () => {
1654
+ await entry.client.disconnect();
1655
+ await entry.client.connect();
1656
+ });
1657
+ await addInternalToolsForEntry(entry);
1658
+ } catch (err) {
1659
+ const translated = toKontextError(err);
1660
+ if (isAuthRecoveryRequired(translated)) {
1661
+ hasUnresolvedAuth = true;
1662
+ if (isTokenExchangeFailure(translated)) {
1663
+ stateController.emitError(translated);
1664
+ }
1665
+ continue;
1666
+ }
1667
+ stateController.emitError(translated);
1668
+ }
1669
+ }
1670
+ if (hasUnresolvedAuth) {
1671
+ stateController.setState("needs_auth");
1672
+ } else if (stateController.state === "needs_auth" && gatewayClient.state === "ready") {
1673
+ stateController.setState("ready");
1674
+ }
1675
+ }
1676
+ return candidates;
1677
+ }
1678
+ async function buildToolInventory(options) {
1679
+ const inventoryKey = JSON.stringify({
1680
+ limit: options?.limit ?? null,
1681
+ runtimeIntegrations: options?.runtimeIntegrations?.map((integration) => integration.id).sort() ?? null
1682
+ });
1683
+ const snapshot = await routeInventory.build(
1684
+ async () => await buildInventoryCandidates(options),
1685
+ {
1686
+ key: inventoryKey,
1687
+ onConflict: (existing, incoming) => routingPolicy.onRouteConflict({
1688
+ toolId: existing.toolId,
1689
+ existing,
1690
+ incoming
1691
+ })
1692
+ }
1693
+ );
1694
+ return {
1695
+ tools: snapshot.tools,
1696
+ conflicts: snapshot.conflicts
1697
+ };
1698
+ }
1699
+ function emitRouteConflicts(conflicts) {
1700
+ for (const conflict of conflicts) {
1701
+ stateController.emitError(
1702
+ toRouteConflictError({
1703
+ toolId: conflict.toolId,
1704
+ kept: conflict.kept,
1705
+ dropped: conflict.dropped
1706
+ })
1707
+ );
1708
+ }
1709
+ }
1710
+ function getInternalIntegrationsMissingTools() {
1711
+ return internalClientRegistry.missingResolved(resolvedInternalListings);
1712
+ }
1713
+ async function disposeInternalClients(mode) {
1714
+ await internalClientRegistry.dispose(mode);
1715
+ }
1716
+ async function ensureConnected() {
1717
+ if (stateController.state === "ready") return;
1718
+ if (stateController.state === "needs_auth" && gatewayClient.state === "ready") {
1719
+ return;
1720
+ }
1721
+ stateController.setState("connecting");
1722
+ try {
1723
+ await gatewayClient.connect();
1724
+ await refreshIntegrationInventory(true);
1725
+ stateController.setState("ready");
1726
+ } catch (err) {
1727
+ const translated = toKontextError(err, {
1728
+ backendId: gatewayBackendId(),
1729
+ source: "gateway",
1730
+ operation: "connect"
1731
+ });
1732
+ if (isAuthRecoveryRequired(translated)) {
1733
+ stateController.setState("needs_auth");
1734
+ } else {
1735
+ stateController.setState("failed");
1736
+ }
1737
+ stateController.emitError(translated);
1738
+ throw translated;
1739
+ }
1740
+ }
1741
+ async function routeForExecution(toolId) {
1742
+ let route = routeInventory.routeFor(toolId);
1743
+ if (route) return route;
1744
+ const inventory = await buildToolInventory();
1745
+ emitRouteConflicts(inventory.conflicts);
1746
+ route = routeInventory.routeFor(toolId);
1747
+ if (route) return route;
1748
+ throw new KontextError(
1749
+ `Unknown tool "${toolId}". Call tools.list() to refresh available tools.`,
1750
+ "kontext_tool_not_found",
1751
+ { meta: { toolId } }
1752
+ );
1753
+ }
1754
+ const orchestrator = {
1755
+ get state() {
1756
+ return stateController.state;
1757
+ },
1758
+ async connect() {
1759
+ await ensureConnected();
1760
+ },
1761
+ async disconnect() {
1762
+ await disposeInternalClients("disconnect");
1763
+ runtimeIntegrations.clear();
1764
+ routeInventory.reset();
1765
+ authSourceQueue.length = 0;
1766
+ await gatewayClient.disconnect();
1767
+ stateController.setState("idle");
1768
+ },
1769
+ async getConnectPageUrl() {
1770
+ await ensureConnected();
1771
+ return await gatewayClient.getConnectPageUrl();
1772
+ },
1773
+ auth: {
1774
+ async signIn() {
1775
+ if (stateController.state === "needs_auth" && gatewayClient.state === "ready") {
1776
+ await refreshIntegrationInventory(true);
1777
+ let unresolvedInternalAuth = false;
1778
+ for (const [
1779
+ integrationId,
1780
+ entry
1781
+ ] of internalClientRegistry.entries()) {
1782
+ try {
1783
+ await runManagedInternalOp(
1784
+ integrationId,
1785
+ () => entry.client.auth.signIn()
1786
+ );
1787
+ } catch (err) {
1788
+ const translated = toKontextError(err);
1789
+ if (isAuthorizationRequired(translated)) {
1790
+ unresolvedInternalAuth = true;
1791
+ continue;
1792
+ }
1793
+ stateController.emitError(translated);
1794
+ }
1795
+ }
1796
+ const inventory = await buildToolInventory();
1797
+ emitRouteConflicts(inventory.conflicts);
1798
+ const missingInternal = getInternalIntegrationsMissingTools();
1799
+ if (!unresolvedInternalAuth && missingInternal.length === 0) {
1800
+ stateController.setState("ready");
1801
+ }
1802
+ return;
1803
+ }
1804
+ await ensureConnected();
1805
+ },
1806
+ async signOut() {
1807
+ await disposeInternalClients("signOut");
1808
+ runtimeIntegrations.clear();
1809
+ routeInventory.reset();
1810
+ authSourceQueue.length = 0;
1811
+ await gatewayClient.auth.signOut();
1812
+ stateController.setState("idle");
1813
+ },
1814
+ async handleCallback(url) {
1815
+ if (internalClientRegistry.size === 0) {
1816
+ try {
1817
+ await refreshIntegrationInventory(true);
1818
+ } catch (err) {
1819
+ stateController.emitError(
1820
+ toKontextError(err, {
1821
+ backendId: gatewayBackendId(),
1822
+ source: "gateway",
1823
+ operation: "auth.handleCallback.preload"
1824
+ })
1825
+ );
1826
+ }
1827
+ }
1828
+ const ordered = [];
1829
+ for (const sourceId of authSourceQueue) {
1830
+ if (sourceId === "gateway") {
1831
+ ordered.push({ client: gatewayClient, sourceId });
1832
+ continue;
1833
+ }
1834
+ const active = internalClientRegistry.get(sourceId);
1835
+ if (active) {
1836
+ ordered.push({ client: active.client, sourceId });
1837
+ }
1838
+ }
1839
+ if (gatewayClient.auth.isCallback(url)) {
1840
+ ordered.push({ client: gatewayClient });
1841
+ }
1842
+ for (const entry of internalClientRegistry.values()) {
1843
+ if (entry.client.auth.isCallback(url)) {
1844
+ ordered.push({ client: entry.client });
1845
+ }
1846
+ }
1847
+ ordered.push({ client: gatewayClient });
1848
+ ordered.push(
1849
+ ...[...internalClientRegistry.values()].sort((a, b) => a.integration.id.localeCompare(b.integration.id)).map((entry) => ({ client: entry.client }))
1850
+ );
1851
+ const unique = [];
1852
+ const seen = /* @__PURE__ */ new Set();
1853
+ for (const entry of ordered) {
1854
+ if (seen.has(entry.client)) continue;
1855
+ seen.add(entry.client);
1856
+ unique.push(entry);
1857
+ }
1858
+ let handledBy;
1859
+ let lastError = void 0;
1860
+ for (const entry of unique) {
1861
+ try {
1862
+ await entry.client.auth.handleCallback(url);
1863
+ handledBy = entry;
1864
+ break;
1865
+ } catch (err) {
1866
+ lastError = err;
1867
+ }
1868
+ }
1869
+ if (handledBy) {
1870
+ for (let idx = authSourceQueue.length - 1; idx >= 0; idx -= 1) {
1871
+ const sourceId = authSourceQueue[idx];
1872
+ const sourceClient = sourceId === "gateway" ? gatewayClient : internalClientRegistry.get(sourceId)?.client;
1873
+ if (sourceClient === handledBy.client) {
1874
+ authSourceQueue.splice(idx, 1);
1875
+ }
1876
+ }
1877
+ }
1878
+ if (!handledBy && lastError) {
1879
+ throw toKontextError(lastError, {
1880
+ backendId: gatewayBackendId(),
1881
+ source: "gateway",
1882
+ operation: "auth.handleCallback"
1883
+ });
1884
+ }
1885
+ try {
1886
+ await ensureConnected();
1887
+ } catch (err) {
1888
+ stateController.emitError(
1889
+ toKontextError(err, {
1890
+ backendId: gatewayBackendId(),
1891
+ source: "gateway",
1892
+ operation: "post_callback_connect"
1893
+ })
1894
+ );
1895
+ }
1896
+ },
1897
+ isCallback(url) {
1898
+ if (gatewayClient.auth.isCallback(url)) return true;
1899
+ for (const entry of internalClientRegistry.values()) {
1900
+ if (entry.client.auth.isCallback(url)) return true;
1901
+ }
1902
+ return false;
1903
+ },
1904
+ get isAuthenticated() {
1905
+ return stateController.state === "ready" || gatewayClient.auth.isAuthenticated;
1906
+ }
1907
+ },
1908
+ integrations: {
1909
+ async list() {
1910
+ await ensureConnected();
1911
+ const discovered = await refreshIntegrationInventory(true);
1912
+ let gatewayStatuses = [];
1913
+ try {
1914
+ gatewayStatuses = await gatewayClient.integrations.list();
1915
+ } catch (err) {
1916
+ stateController.emitError(
1917
+ toKontextError(err, {
1918
+ backendId: gatewayBackendId(),
1919
+ source: "gateway",
1920
+ operation: "integrations.list"
1921
+ })
1922
+ );
1923
+ }
1924
+ const gatewayById = new Map(gatewayStatuses.map((i) => [i.id, i]));
1925
+ const needsInternalConnectLink = discovered.some(
1926
+ (i) => i.category === "internal_mcp_credentials" && !i.connection?.connected
1927
+ );
1928
+ let sharedConnectUrl;
1929
+ if (needsInternalConnectLink) {
1930
+ try {
1931
+ sharedConnectUrl = (await gatewayClient.getConnectPageUrl()).connectUrl;
1932
+ } catch {
1933
+ sharedConnectUrl = void 0;
1934
+ }
1935
+ }
1936
+ return discovered.map((integration) => {
1937
+ const gatewayStatus = gatewayById.get(integration.id);
1938
+ const connected = gatewayStatus?.connected ?? integration.connection?.connected ?? false;
1939
+ const connectUrl = gatewayStatus?.connectUrl ?? (!connected && integration.category === "internal_mcp_credentials" ? sharedConnectUrl : void 0);
1940
+ const reason = gatewayStatus?.reason ?? (!connected && integration.category === "internal_mcp_credentials" ? "credentials_required" : void 0);
1941
+ return {
1942
+ id: integration.id,
1943
+ name: integration.name,
1944
+ connected,
1945
+ connectUrl,
1946
+ reason
1947
+ };
1948
+ });
1949
+ }
1950
+ },
1951
+ tools: {
1952
+ async list(options) {
1953
+ await ensureConnected();
1954
+ let inventory = await buildToolInventory(options);
1955
+ const missingInternal = getInternalIntegrationsMissingTools();
1956
+ if (missingInternal.length > 0) {
1957
+ const refreshed = await refreshIntegrationInventory(true);
1958
+ inventory = await buildToolInventory({
1959
+ ...options,
1960
+ runtimeIntegrations: refreshed
1961
+ });
1962
+ }
1963
+ emitRouteConflicts(inventory.conflicts);
1964
+ const unresolvedInternal = getInternalIntegrationsMissingTools();
1965
+ if (stateController.state === "needs_auth" && gatewayClient.state === "ready" && unresolvedInternal.length === 0) {
1966
+ stateController.setState("ready");
1967
+ }
1968
+ return inventory.tools;
1969
+ },
1970
+ async execute(toolId, args) {
1971
+ await ensureConnected();
1972
+ const route = await routeForExecution(toolId);
1973
+ try {
1974
+ if (route.source === "gateway") {
1975
+ return await gatewayClient.tools.execute(route.backendToolId, args);
1976
+ }
1977
+ const integrationId = route.integrationId;
1978
+ if (!integrationId) {
1979
+ throw new KontextError(
1980
+ `Route for tool "${toolId}" is missing integration metadata.`,
1981
+ "kontext_tool_not_found",
1982
+ { meta: { toolId, route } }
1983
+ );
1984
+ }
1985
+ let entry = internalClientRegistry.get(integrationId);
1986
+ if (!entry) {
1987
+ await refreshIntegrationInventory(true);
1988
+ entry = internalClientRegistry.get(integrationId);
1989
+ }
1990
+ if (!entry) {
1991
+ throw new KontextError(
1992
+ `Internal integration "${integrationId}" is no longer attached.`,
1993
+ "kontext_tool_not_found",
1994
+ { meta: { integrationId } }
1995
+ );
1996
+ }
1997
+ await ensureInternalResourceToken(entry.integration);
1998
+ try {
1999
+ const executeInternal = async () => await withTransientRetry(
2000
+ async () => await runManagedInternalOp(
2001
+ integrationId,
2002
+ () => entry.client.tools.execute(route.backendToolId, args)
2003
+ )
2004
+ );
2005
+ return await executeInternal();
2006
+ } catch (innerErr) {
2007
+ const innerTranslated = toKontextError(innerErr, {
2008
+ backendId: route.backendId,
2009
+ source: route.source,
2010
+ integrationId: route.integrationId,
2011
+ operation: "tools.execute",
2012
+ toolId
2013
+ });
2014
+ throw innerTranslated;
2015
+ }
2016
+ } catch (err) {
2017
+ const translated = toKontextError(err, {
2018
+ backendId: route.backendId,
2019
+ source: route.source,
2020
+ integrationId: route.integrationId,
2021
+ operation: "tools.execute",
2022
+ toolId
2023
+ });
2024
+ if (isAuthRecoveryRequired(translated)) {
2025
+ stateController.setState("needs_auth");
2026
+ }
2027
+ stateController.emitError(translated);
2028
+ throw translated;
2029
+ }
2030
+ }
2031
+ },
2032
+ on(event, handler) {
2033
+ if (event === "stateChange") {
2034
+ return stateController.on("stateChange", handler);
2035
+ }
2036
+ return stateController.on("error", handler);
2037
+ },
2038
+ get mcp() {
2039
+ return gatewayClient.mcp;
2040
+ }
2041
+ };
2042
+ return orchestrator;
2043
+ }
2044
+
2045
+ // src/client/index.ts
2046
+ var META_TOOL_NAMES = /* @__PURE__ */ new Set(["SEARCH_TOOLS", "EXECUTE_TOOL"]);
2047
+ function hasMetaTools(tools) {
2048
+ let hasSearch = false;
2049
+ let hasExecute = false;
2050
+ for (const tool of tools) {
2051
+ if (tool.name === "SEARCH_TOOLS") hasSearch = true;
2052
+ if (tool.name === "EXECUTE_TOOL") hasExecute = true;
2053
+ }
2054
+ return hasSearch && hasExecute;
2055
+ }
2056
+ function extractJsonResourceText(result) {
2057
+ if (!result || typeof result !== "object") return null;
2058
+ const content = result.content;
2059
+ if (!Array.isArray(content)) return null;
2060
+ for (const item of content) {
2061
+ if (item.type === "resource" && item.resource?.mimeType === "application/json" && item.resource.text) {
2062
+ return item.resource.text;
2063
+ }
2064
+ }
2065
+ return null;
2066
+ }
2067
+ function extractTextContent(result) {
2068
+ if (!result || typeof result !== "object") return String(result ?? "");
2069
+ const r = result;
2070
+ if (r.content && Array.isArray(r.content)) {
2071
+ const texts = r.content.filter((c) => c.type === "text" && c.text).map((c) => c.text);
2072
+ if (texts.length > 0) return texts.join("\n");
2073
+ const resourceTexts = r.content.filter((c) => c.type === "resource" && c.resource?.text).map((c) => c.resource.text);
2074
+ if (resourceTexts.length > 0) {
2075
+ return resourceTexts.map((text) => {
2076
+ try {
2077
+ return extractTextContent(JSON.parse(text));
2078
+ } catch {
2079
+ return text;
2080
+ }
2081
+ }).join("\n");
2082
+ }
2083
+ return JSON.stringify(r.content);
2084
+ }
2085
+ return JSON.stringify(result);
2086
+ }
2087
+ function translateError(err) {
2088
+ if (isKontextError(err)) return err;
2089
+ if (!(err instanceof Error)) {
2090
+ return new KontextError(String(err), "kontext_unknown_error");
2091
+ }
2092
+ const props = err;
2093
+ if (props.code === -32042) {
2094
+ const elicitations = props.elicitations ?? props.data?.elicitations;
2095
+ const elicitation = elicitations?.[0];
2096
+ return new IntegrationConnectionRequiredError(
2097
+ elicitation?.integrationId ?? "unknown",
2098
+ {
2099
+ integrationName: elicitation?.integrationName,
2100
+ connectUrl: elicitation?.url,
2101
+ message: elicitation?.message,
2102
+ cause: err
2103
+ }
2104
+ );
2105
+ }
2106
+ const statusCode = props.statusCode ?? props.status;
2107
+ if (typeof statusCode === "number" && statusCode >= 400) {
2108
+ if (statusCode === 401) {
2109
+ return new AuthorizationRequiredError(err.message, { cause: err });
2110
+ }
2111
+ return new KontextError(err.message, "kontext_server_error", {
2112
+ statusCode,
2113
+ cause: err
2114
+ });
2115
+ }
2116
+ if (isUnauthorizedError(err)) {
2117
+ return new AuthorizationRequiredError(err.message, { cause: err });
2118
+ }
2119
+ if (isNetworkError(err)) {
2120
+ return new NetworkError(err.message, { cause: err });
2121
+ }
2122
+ return new KontextError(err.message, "kontext_unknown_error", {
2123
+ cause: err
2124
+ });
2125
+ }
2126
+ function createSingleEndpointKontextClient(config) {
2127
+ if (!config.clientId) {
2128
+ throw new ConfigError(
2129
+ "clientId is required. Pass it in KontextClientConfig or set KONTEXT_CLIENT_ID.",
2130
+ "kontext_config_missing_client_id"
2131
+ );
2132
+ }
2133
+ if (!config.redirectUri) {
2134
+ throw new ConfigError(
2135
+ "redirectUri is required. Set it to the URL where OAuth should redirect after authorization.",
2136
+ "kontext_config_missing_redirect_uri"
2137
+ );
2138
+ }
2139
+ if (!config.onAuthRequired) {
2140
+ throw new ConfigError(
2141
+ "onAuthRequired callback is required. Provide a function that opens the OAuth URL.",
2142
+ "kontext_config_missing_auth_handler"
2143
+ );
2144
+ }
2145
+ let _state = "idle";
2146
+ const _listeners = /* @__PURE__ */ new Map();
2147
+ let _metaToolMode = null;
2148
+ const mcp = new KontextMcp({
2149
+ clientId: config.clientId,
2150
+ url: config.url,
2151
+ server: config.serverUrl,
2152
+ redirectUri: config.redirectUri,
2153
+ storage: config.storage,
2154
+ sessionKey: config.sessionKey,
2155
+ onAuthRequired: config.onAuthRequired,
2156
+ // Route MCP elicitation to the high-level callback.
2157
+ // KontextMcp calls this then re-throws; client.tools.execute() catches
2158
+ // the re-thrown error and handles translation.
2159
+ onElicitationUrl: config.onIntegrationRequired ? (entry) => {
2160
+ config.onIntegrationRequired(entry.url, {
2161
+ id: entry.integrationId ?? "unknown",
2162
+ name: entry.integrationName ?? entry.message
2163
+ });
2164
+ } : void 0
2165
+ });
2166
+ function setState(newState) {
2167
+ if (_state === newState) return;
2168
+ _state = newState;
2169
+ try {
2170
+ config.onStateChange?.(newState);
2171
+ } catch {
2172
+ }
2173
+ const handlers = _listeners.get("stateChange");
2174
+ if (handlers) {
2175
+ for (const handler of handlers) {
2176
+ try {
2177
+ handler(newState);
2178
+ } catch {
2179
+ }
2180
+ }
2181
+ }
2182
+ }
2183
+ function emitError(error) {
2184
+ const handlers = _listeners.get("error");
2185
+ if (handlers) {
2186
+ for (const handler of handlers) {
2187
+ try {
2188
+ handler(error);
2189
+ } catch {
2190
+ }
2191
+ }
2192
+ }
2193
+ }
2194
+ async function fetchGatewayTools(limit = 100) {
2195
+ const result = await mcp.callTool("SEARCH_TOOLS", { limit });
2196
+ const jsonText = extractJsonResourceText(result);
2197
+ if (!jsonText) {
2198
+ throw new KontextError(
2199
+ "SEARCH_TOOLS did not return JSON resource content. The server may not support the gateway protocol.",
2200
+ "kontext_tool_response_empty"
2201
+ );
2202
+ }
2203
+ let parsed;
2204
+ try {
2205
+ parsed = JSON.parse(jsonText);
2206
+ } catch (e) {
2207
+ throw new KontextError(
2208
+ `SEARCH_TOOLS returned invalid JSON: ${e instanceof Error ? e.message : String(e)}`,
2209
+ "kontext_tool_response_invalid_json"
2210
+ );
2211
+ }
2212
+ if (Array.isArray(parsed)) {
2213
+ return { tools: parsed, errors: [] };
2214
+ }
2215
+ if (parsed && typeof parsed === "object") {
2216
+ const obj = parsed;
2217
+ return {
2218
+ tools: Array.isArray(obj.items) ? obj.items : [],
2219
+ errors: Array.isArray(obj.errors) ? obj.errors : [],
2220
+ elicitations: Array.isArray(obj.elicitations) ? obj.elicitations : void 0
2221
+ };
2222
+ }
2223
+ throw new KontextError(
2224
+ "SEARCH_TOOLS response was not a JSON array or object. Check the server version.",
2225
+ "kontext_tool_response_unexpected"
2226
+ );
2227
+ }
2228
+ function toKontextTool(tool) {
2229
+ return {
2230
+ id: tool.id,
2231
+ name: tool.name,
2232
+ description: tool.description,
2233
+ inputSchema: tool.inputSchema,
2234
+ server: tool.server ? { id: tool.server.id ?? "", name: tool.server.name } : void 0
2235
+ };
2236
+ }
2237
+ async function ensureConnected() {
2238
+ if (_state === "ready" && mcp.isConnected) return;
2239
+ setState("connecting");
2240
+ try {
2241
+ const mcpTools = await mcp.listTools();
2242
+ _metaToolMode = hasMetaTools(mcpTools);
2243
+ setState("ready");
2244
+ } catch (err) {
2245
+ const translated = translateError(err);
2246
+ if (translated instanceof AuthorizationRequiredError) {
2247
+ setState("needs_auth");
2248
+ } else {
2249
+ setState("failed");
2250
+ }
2251
+ emitError(translated);
2252
+ throw translated;
2253
+ }
2254
+ }
2255
+ const client = {
2256
+ get state() {
2257
+ return _state;
2258
+ },
2259
+ async connect() {
2260
+ await ensureConnected();
2261
+ },
2262
+ async disconnect() {
2263
+ await mcp.disconnect();
2264
+ _metaToolMode = null;
2265
+ setState("idle");
2266
+ },
2267
+ async getConnectPageUrl() {
2268
+ await ensureConnected();
2269
+ try {
2270
+ return await mcp.createConnectSession();
2271
+ } catch (err) {
2272
+ const translated = translateError(err);
2273
+ if (translated instanceof AuthorizationRequiredError) {
2274
+ setState("needs_auth");
2275
+ }
2276
+ throw translated;
2277
+ }
2278
+ },
2279
+ auth: {
2280
+ async signIn() {
2281
+ await ensureConnected();
2282
+ },
2283
+ async signOut() {
2284
+ await mcp.clearAuth();
2285
+ _metaToolMode = null;
2286
+ setState("idle");
2287
+ },
2288
+ async handleCallback(url) {
2289
+ await mcp.handleCallback(url);
2290
+ try {
2291
+ await ensureConnected();
2292
+ } catch (err) {
2293
+ emitError(translateError(err));
2294
+ }
2295
+ },
2296
+ isCallback(url) {
2297
+ return mcp.isCallback(url);
2298
+ },
2299
+ get isAuthenticated() {
2300
+ return _state === "ready" || mcp.isConnected;
2301
+ }
2302
+ },
2303
+ integrations: {
2304
+ async list() {
2305
+ await ensureConnected();
2306
+ try {
2307
+ const { tools, errors, elicitations } = await fetchGatewayTools();
2308
+ const statuses = parseIntegrationStatus(tools, errors, elicitations);
2309
+ const errorMap = new Map(errors.map((e) => [e.serverId, e.reason]));
2310
+ return statuses.map((s) => {
2311
+ const reason = errorMap.get(s.id);
2312
+ return reason ? { ...s, reason } : s;
2313
+ });
2314
+ } catch (err) {
2315
+ const translated = translateError(err);
2316
+ if (translated instanceof AuthorizationRequiredError) {
2317
+ setState("needs_auth");
2318
+ }
2319
+ throw translated;
2320
+ }
2321
+ }
2322
+ },
2323
+ tools: {
2324
+ async list(options) {
2325
+ await ensureConnected();
2326
+ try {
2327
+ const mcpTools = await mcp.listTools();
2328
+ const nonMetaTools = mcpTools.filter(
2329
+ (t) => !META_TOOL_NAMES.has(t.name)
2330
+ );
2331
+ if (nonMetaTools.length > 0 || !hasMetaTools(mcpTools)) {
2332
+ _metaToolMode = false;
2333
+ return nonMetaTools.map((t) => ({
2334
+ id: t.name,
2335
+ name: t.name,
2336
+ description: t.description,
2337
+ inputSchema: t.inputSchema
2338
+ }));
2339
+ }
2340
+ _metaToolMode = true;
2341
+ const { tools, elicitations } = await fetchGatewayTools(
2342
+ options?.limit
2343
+ );
2344
+ if (elicitations?.length && config.onIntegrationRequired) {
2345
+ for (const e of elicitations) {
2346
+ if (e.url) {
2347
+ config.onIntegrationRequired(e.url, {
2348
+ id: e.integrationId ?? "",
2349
+ name: e.integrationName ?? e.message
2350
+ });
2351
+ }
2352
+ }
2353
+ }
2354
+ return tools.map(toKontextTool);
2355
+ } catch (err) {
2356
+ const translated = translateError(err);
2357
+ if (translated instanceof AuthorizationRequiredError) {
2358
+ setState("needs_auth");
2359
+ }
2360
+ throw translated;
2361
+ }
2362
+ },
2363
+ async execute(toolId, args) {
2364
+ await ensureConnected();
2365
+ if (_metaToolMode === null) {
2366
+ const mcpTools = await mcp.listTools();
2367
+ _metaToolMode = hasMetaTools(mcpTools);
2368
+ }
2369
+ try {
2370
+ const result = _metaToolMode ? await mcp.callTool("EXECUTE_TOOL", {
2371
+ tool_id: toolId,
2372
+ tool_arguments: args ?? {}
2373
+ }) : await mcp.callTool(toolId, args);
2374
+ return { content: extractTextContent(result), raw: result };
2375
+ } catch (err) {
2376
+ const translated = translateError(err);
2377
+ if (translated instanceof AuthorizationRequiredError) {
2378
+ setState("needs_auth");
2379
+ }
2380
+ throw translated;
2381
+ }
2382
+ }
2383
+ },
2384
+ on(event, handler) {
2385
+ if (!_listeners.has(event)) {
2386
+ _listeners.set(event, /* @__PURE__ */ new Set());
2387
+ }
2388
+ _listeners.get(event).add(handler);
2389
+ return () => {
2390
+ _listeners.get(event)?.delete(handler);
2391
+ };
2392
+ },
2393
+ get mcp() {
2394
+ return mcp;
2395
+ }
2396
+ };
2397
+ return client;
2398
+ }
2399
+ function createKontextClient(config) {
2400
+ if (config.url !== void 0) {
2401
+ if (typeof config.url !== "string" || config.url.trim().length === 0) {
2402
+ throw new ConfigError(
2403
+ "url must be a non-empty string. Omit url for hybrid mode, or provide a full MCP endpoint URL.",
2404
+ "kontext_config_invalid_url"
2405
+ );
2406
+ }
2407
+ return createSingleEndpointKontextClient(config);
2408
+ }
2409
+ return createKontextOrchestrator(config);
2410
+ }
2411
+
2412
+ exports.createKontextClient = createKontextClient;
2413
+ exports.createSingleEndpointKontextClient = createSingleEndpointKontextClient;
2414
+ //# sourceMappingURL=index.cjs.map
2415
+ //# sourceMappingURL=index.cjs.map