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