@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,797 @@
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
+ var AuthorizationRequiredError = class extends KontextError {
114
+ authorizationUrl;
115
+ constructor(message = "Authorization required. Complete the OAuth flow to continue.", options) {
116
+ super(message, "kontext_authorization_required", {
117
+ statusCode: 401,
118
+ ...options
119
+ });
120
+ this.name = "AuthorizationRequiredError";
121
+ this.authorizationUrl = options?.authorizationUrl;
122
+ }
123
+ };
124
+ var OAuthError = class extends KontextError {
125
+ errorCode;
126
+ errorDescription;
127
+ constructor(message, code, options) {
128
+ super(message, code, {
129
+ statusCode: options?.statusCode ?? 400,
130
+ ...options
131
+ });
132
+ this.name = "OAuthError";
133
+ this.errorCode = options?.errorCode;
134
+ this.errorDescription = options?.errorDescription;
135
+ }
136
+ };
137
+ function errorProps(err) {
138
+ return err;
139
+ }
140
+ function isUnauthorizedError(err) {
141
+ const props = errorProps(err);
142
+ if (props.statusCode === 401 || props.status === 401) return true;
143
+ if (err.name === "UnauthorizedError") return true;
144
+ if (err.message === "Unauthorized") return true;
145
+ return false;
146
+ }
147
+
148
+ // src/oauth/provider.ts
149
+ var KontextOAuthProvider = class {
150
+ config;
151
+ storagePrefix;
152
+ pendingState = null;
153
+ expiryBufferMs = 60 * 1e3;
154
+ constructor(config) {
155
+ this.config = config;
156
+ this.storagePrefix = createStorageKey(config.clientId, config.sessionKey);
157
+ }
158
+ /**
159
+ * The redirect URL for OAuth callbacks
160
+ */
161
+ get redirectUrl() {
162
+ return this.config.redirectUri;
163
+ }
164
+ /**
165
+ * OAuth client metadata
166
+ */
167
+ get clientMetadata() {
168
+ return {
169
+ redirect_uris: [this.config.redirectUri],
170
+ client_name: this.config.clientName,
171
+ grant_types: ["authorization_code", "refresh_token"],
172
+ response_types: ["code"],
173
+ token_endpoint_auth_method: "none"
174
+ // Public client
175
+ };
176
+ }
177
+ /**
178
+ * Generate a random state parameter for OAuth CSRF protection
179
+ */
180
+ state() {
181
+ const array = new Uint8Array(32);
182
+ if (globalThis.crypto?.getRandomValues) {
183
+ globalThis.crypto.getRandomValues(array);
184
+ } else {
185
+ array.set(randomBytes(32));
186
+ }
187
+ const state = Array.from(
188
+ array,
189
+ (byte) => byte.toString(16).padStart(2, "0")
190
+ ).join("");
191
+ this.pendingState = state;
192
+ void this.config.storage.setJson(
193
+ this.getStorageKey(StorageKeys.STATE),
194
+ state
195
+ );
196
+ return state;
197
+ }
198
+ /**
199
+ * Returns the client information (client_id)
200
+ * Since we're a public client with pre-registered credentials,
201
+ * we don't use dynamic client registration.
202
+ */
203
+ async clientInformation() {
204
+ return {
205
+ client_id: this.config.clientId
206
+ };
207
+ }
208
+ /**
209
+ * Load stored OAuth tokens
210
+ */
211
+ async tokens() {
212
+ const key = this.getStorageKey(StorageKeys.TOKENS);
213
+ return this.config.storage.getJson(key);
214
+ }
215
+ /**
216
+ * Save OAuth tokens after successful authorization
217
+ */
218
+ async saveTokens(tokens) {
219
+ const key = this.getStorageKey(StorageKeys.TOKENS);
220
+ await this.config.storage.setJson(key, this.withIssuedAt(tokens));
221
+ }
222
+ /**
223
+ * Redirect the user agent to the authorization URL
224
+ */
225
+ async redirectToAuthorization(authorizationUrl) {
226
+ await this.config.onRedirectToAuthorization(authorizationUrl);
227
+ }
228
+ /**
229
+ * Save the PKCE code verifier before redirecting to authorization
230
+ */
231
+ async saveCodeVerifier(codeVerifier) {
232
+ const key = this.getStorageKey(StorageKeys.CODE_VERIFIER);
233
+ await this.config.storage.setJson(key, codeVerifier);
234
+ }
235
+ /**
236
+ * Load the PKCE code verifier for token exchange
237
+ */
238
+ async codeVerifier() {
239
+ const key = this.getStorageKey(StorageKeys.CODE_VERIFIER);
240
+ const verifier = await this.config.storage.getJson(key);
241
+ if (!verifier) {
242
+ throw new OAuthError(
243
+ "No PKCE code verifier found in storage. The OAuth flow may have expired or storage was cleared. Restart the auth flow.",
244
+ "kontext_oauth_code_verifier_missing"
245
+ );
246
+ }
247
+ return verifier;
248
+ }
249
+ /**
250
+ * Invalidate stored credentials
251
+ */
252
+ async invalidateCredentials(scope) {
253
+ if (scope === "all" || scope === "tokens") {
254
+ const tokensKey = this.getStorageKey(StorageKeys.TOKENS);
255
+ await this.config.storage.setJson(tokensKey, void 0);
256
+ const identityKey = this.getStorageKey(StorageKeys.IDENTITY_TOKENS);
257
+ await this.config.storage.setJson(identityKey, void 0);
258
+ }
259
+ if (scope === "all" || scope === "verifier") {
260
+ const verifierKey = this.getStorageKey(StorageKeys.CODE_VERIFIER);
261
+ await this.config.storage.setJson(verifierKey, void 0);
262
+ }
263
+ if (scope === "all") {
264
+ this.pendingState = null;
265
+ const stateKey = this.getStorageKey(StorageKeys.STATE);
266
+ await this.config.storage.setJson(stateKey, void 0);
267
+ }
268
+ }
269
+ /**
270
+ * Clear all stored state (tokens, verifier, etc.)
271
+ * Call this to force re-authentication
272
+ */
273
+ async clearAll() {
274
+ await this.invalidateCredentials("all");
275
+ }
276
+ /**
277
+ * Check if we have valid (non-expired) tokens
278
+ */
279
+ async hasValidTokens() {
280
+ const storedTokens = await this.tokens();
281
+ return this.isTokenValid(storedTokens);
282
+ }
283
+ // ==========================================================================
284
+ // Pattern B: Identity and Resource Token Management (RFC 8693)
285
+ // ==========================================================================
286
+ /**
287
+ * Save identity tokens (no audience)
288
+ * These are the tokens obtained from the initial OAuth flow before token exchange.
289
+ */
290
+ async saveIdentityTokens(tokens) {
291
+ const key = this.getStorageKey(StorageKeys.IDENTITY_TOKENS);
292
+ await this.config.storage.setJson(key, this.withIssuedAt(tokens));
293
+ }
294
+ /**
295
+ * Load identity tokens
296
+ * Returns the identity tokens obtained from the initial OAuth flow.
297
+ */
298
+ async identityTokens() {
299
+ const key = this.getStorageKey(StorageKeys.IDENTITY_TOKENS);
300
+ return this.config.storage.getJson(key);
301
+ }
302
+ /**
303
+ * Save resource-scoped tokens for a specific resource
304
+ *
305
+ * @param resource The resource identifier (e.g., "mcp-gateway")
306
+ * @param tokens The resource-scoped tokens
307
+ */
308
+ async saveResourceTokens(resource, tokens) {
309
+ const key = this.getStorageKey(resourceTokenKey(resource));
310
+ await this.config.storage.setJson(key, this.withIssuedAt(tokens));
311
+ }
312
+ /**
313
+ * Load resource-scoped tokens for a specific resource
314
+ *
315
+ * @param resource The resource identifier (e.g., "mcp-gateway")
316
+ * @returns The resource-scoped tokens, or undefined if not found
317
+ */
318
+ async resourceTokens(resource) {
319
+ const key = this.getStorageKey(resourceTokenKey(resource));
320
+ return this.config.storage.getJson(key);
321
+ }
322
+ /**
323
+ * Clear resource tokens for a specific resource
324
+ *
325
+ * @param resource The resource identifier (e.g., "mcp-gateway")
326
+ */
327
+ async clearResourceTokens(resource) {
328
+ const key = this.getStorageKey(resourceTokenKey(resource));
329
+ await this.config.storage.setJson(key, void 0);
330
+ }
331
+ /**
332
+ * Check if we have valid identity tokens
333
+ */
334
+ async hasValidIdentityTokens() {
335
+ const tokens = await this.identityTokens();
336
+ return this.isTokenValid(tokens);
337
+ }
338
+ /**
339
+ * Check if we have valid resource tokens for a specific resource
340
+ *
341
+ * @param resource The resource identifier
342
+ */
343
+ async hasValidResourceTokens(resource) {
344
+ const tokens = await this.resourceTokens(resource);
345
+ return this.isTokenValid(tokens);
346
+ }
347
+ async validateState(state) {
348
+ if (!state) {
349
+ return false;
350
+ }
351
+ const key = this.getStorageKey(StorageKeys.STATE);
352
+ const storedState = this.pendingState ?? await this.config.storage.getJson(key);
353
+ const isValid = storedState === state;
354
+ if (isValid) {
355
+ this.pendingState = null;
356
+ await this.config.storage.setJson(key, void 0);
357
+ }
358
+ return isValid;
359
+ }
360
+ withIssuedAt(tokens) {
361
+ if (!tokens.expires_in) {
362
+ return tokens;
363
+ }
364
+ return { ...tokens, issued_at: Date.now() };
365
+ }
366
+ isTokenValid(tokens) {
367
+ if (!tokens?.access_token) {
368
+ return false;
369
+ }
370
+ if (!tokens.expires_in) {
371
+ return true;
372
+ }
373
+ const issuedAt = tokens.issued_at;
374
+ if (!issuedAt) {
375
+ return true;
376
+ }
377
+ const expiresAt = issuedAt + tokens.expires_in * 1e3;
378
+ return Date.now() < expiresAt - this.expiryBufferMs;
379
+ }
380
+ getStorageKey(key) {
381
+ return `${this.storagePrefix}:${key}`;
382
+ }
383
+ };
384
+ function parseOAuthCallback(callbackUrl) {
385
+ const url = typeof callbackUrl === "string" ? new URL(callbackUrl) : callbackUrl;
386
+ const params = url.searchParams;
387
+ const error = params.get("error");
388
+ if (error) {
389
+ return {
390
+ error,
391
+ errorDescription: params.get("error_description") ?? void 0
392
+ };
393
+ }
394
+ return {
395
+ code: params.get("code") ?? void 0,
396
+ state: params.get("state") ?? void 0
397
+ };
398
+ }
399
+
400
+ // src/mcp/client.ts
401
+ var DEFAULT_SERVER = "https://api.kontext.dev";
402
+ function normalizeKontextServerUrl(server) {
403
+ let url = server.replace(/\/$/, "");
404
+ url = url.replace(/\/api\/v1\/?$/, "").replace(/\/mcp\/?$/, "");
405
+ url = url.replace(/\/$/, "");
406
+ return url;
407
+ }
408
+ var KontextMcp = class {
409
+ config;
410
+ storage;
411
+ oauthProvider;
412
+ transport = null;
413
+ client = null;
414
+ _isConnected = false;
415
+ _pendingConnect = null;
416
+ _pendingAuthFlow = null;
417
+ _authFlowResolve = null;
418
+ constructor(config) {
419
+ this.config = config;
420
+ this.storage = config.storage ?? new MemoryStorage();
421
+ this.oauthProvider = new KontextOAuthProvider({
422
+ clientId: config.clientId,
423
+ redirectUri: config.redirectUri,
424
+ storage: this.storage,
425
+ sessionKey: config.sessionKey ?? "default",
426
+ clientName: config.clientName,
427
+ onRedirectToAuthorization: async (url) => {
428
+ this._pendingAuthFlow = new Promise((resolve) => {
429
+ this._authFlowResolve = resolve;
430
+ });
431
+ const result = await config.onAuthRequired(url);
432
+ if (result) {
433
+ await this.handleCallback(result);
434
+ }
435
+ }
436
+ });
437
+ }
438
+ /**
439
+ * Check if we're currently connected
440
+ */
441
+ get isConnected() {
442
+ return this._isConnected;
443
+ }
444
+ /**
445
+ * Get the underlying MCP client for advanced usage
446
+ */
447
+ get mcpClient() {
448
+ return this.client;
449
+ }
450
+ /**
451
+ * Get the session ID from the transport
452
+ */
453
+ get sessionId() {
454
+ return this.transport?.sessionId;
455
+ }
456
+ /**
457
+ * Get the server base URL
458
+ */
459
+ get serverUrl() {
460
+ return normalizeKontextServerUrl(this.config.server ?? DEFAULT_SERVER);
461
+ }
462
+ /**
463
+ * Get the MCP endpoint URL.
464
+ * When `url` is provided, use it directly. Otherwise derive from server.
465
+ */
466
+ get mcpEndpointUrl() {
467
+ return this.config.url ?? `${this.serverUrl}/mcp`;
468
+ }
469
+ /**
470
+ * List available tools from the server
471
+ *
472
+ * This will automatically handle authentication if needed.
473
+ */
474
+ async listTools() {
475
+ await this.ensureConnected();
476
+ const response = await this.client.listTools();
477
+ return response.tools;
478
+ }
479
+ /**
480
+ * Call a tool
481
+ *
482
+ * This will automatically handle authentication if needed.
483
+ *
484
+ * @param name The tool name
485
+ * @param args The tool arguments
486
+ */
487
+ async callTool(name, args) {
488
+ await this.ensureConnected();
489
+ try {
490
+ const result = await this.client.callTool({
491
+ name,
492
+ arguments: args
493
+ });
494
+ return result;
495
+ } catch (error) {
496
+ if (error instanceof UrlElicitationRequiredError && this.config.onElicitationUrl) {
497
+ for (const elicitation of error.elicitations) {
498
+ await this.config.onElicitationUrl({
499
+ url: elicitation.url,
500
+ message: elicitation.message ?? "Action required",
501
+ elicitationId: elicitation.elicitationId ?? "",
502
+ integrationId: elicitation.integrationId,
503
+ integrationName: elicitation.integrationName
504
+ });
505
+ }
506
+ }
507
+ throw error;
508
+ }
509
+ }
510
+ /**
511
+ * Create a connect session for the hosted connect UI.
512
+ *
513
+ * Returns a URL that can be opened in a browser to let the user
514
+ * connect integrations proactively (before hitting -32042 errors).
515
+ */
516
+ async createConnectSession() {
517
+ const tokens = await this.oauthProvider.tokens();
518
+ if (!tokens?.access_token) {
519
+ throw new AuthorizationRequiredError(
520
+ "Authorization required. Complete the OAuth flow first."
521
+ );
522
+ }
523
+ const response = await fetch(`${this.serverUrl}/mcp/connect-session`, {
524
+ method: "POST",
525
+ headers: {
526
+ Authorization: `Bearer ${tokens.access_token}`,
527
+ "Content-Type": "application/json"
528
+ }
529
+ });
530
+ if (response.status === 401) {
531
+ throw new AuthorizationRequiredError(
532
+ "Access token expired or invalid. Re-authenticate and retry."
533
+ );
534
+ }
535
+ if (!response.ok) {
536
+ throw new KontextError(
537
+ `Failed to create connect session: HTTP ${response.status}`,
538
+ "kontext_connect_session_failed",
539
+ { statusCode: response.status }
540
+ );
541
+ }
542
+ return await response.json();
543
+ }
544
+ /**
545
+ * List integrations attached to the current application/runtime identity.
546
+ *
547
+ * This is used by higher-level orchestrators to discover mixed integration
548
+ * topologies (gateway + internal credential integrations).
549
+ */
550
+ async listRuntimeIntegrations() {
551
+ const tokens = await this.oauthProvider.tokens();
552
+ if (!tokens?.access_token) {
553
+ throw new AuthorizationRequiredError(
554
+ "Authorization required. Complete the OAuth flow first."
555
+ );
556
+ }
557
+ const response = await fetch(`${this.serverUrl}/mcp/integrations`, {
558
+ method: "GET",
559
+ headers: {
560
+ Authorization: `Bearer ${tokens.access_token}`
561
+ }
562
+ });
563
+ if (response.status === 401) {
564
+ throw new AuthorizationRequiredError(
565
+ "Access token expired or invalid. Re-authenticate and retry."
566
+ );
567
+ }
568
+ if (!response.ok) {
569
+ throw new KontextError(
570
+ `Failed to list runtime integrations: HTTP ${response.status}`,
571
+ "kontext_runtime_integrations_failed",
572
+ { statusCode: response.status }
573
+ );
574
+ }
575
+ const payload = await response.json();
576
+ const items = Array.isArray(payload?.items) ? payload.items : [];
577
+ return items.map((item) => {
578
+ const id = typeof item.id === "string" ? item.id : "";
579
+ const name = typeof item.name === "string" ? item.name : id;
580
+ const url = typeof item.url === "string" ? item.url : "";
581
+ if (!id || !url) return null;
582
+ const category = item.category === "internal_mcp_credentials" ? "internal_mcp_credentials" : "gateway_remote_mcp";
583
+ const connectType = item.connectType === "credentials" || item.connectType === "oauth" || item.connectType === "none" ? item.connectType : category === "internal_mcp_credentials" ? "credentials" : item.authMode === "oauth" ? "oauth" : "none";
584
+ const rawConnection = item.connection && typeof item.connection === "object" ? item.connection : void 0;
585
+ const connected = rawConnection && typeof rawConnection.connected === "boolean" ? rawConnection.connected : false;
586
+ const status = rawConnection?.status === "connected" ? "connected" : "disconnected";
587
+ return {
588
+ id,
589
+ name,
590
+ url,
591
+ category,
592
+ connectType,
593
+ authMode: item.authMode === "oauth" || item.authMode === "user_token" || item.authMode === "server_token" || item.authMode === "none" ? item.authMode : void 0,
594
+ credentialSchema: item.credentialSchema,
595
+ requiresOauth: typeof item.requiresOauth === "boolean" ? item.requiresOauth : void 0,
596
+ connection: rawConnection ? {
597
+ connected,
598
+ status,
599
+ expiresAt: typeof rawConnection.expiresAt === "string" ? rawConnection.expiresAt : void 0,
600
+ displayName: typeof rawConnection.displayName === "string" ? rawConnection.displayName : void 0
601
+ } : void 0
602
+ };
603
+ }).filter((item) => item !== null);
604
+ }
605
+ /**
606
+ * Handle an OAuth callback URL
607
+ *
608
+ * Call this after the user has been redirected back from authorization.
609
+ * This is required for web apps where `onAuthRequired` redirects instead of waiting.
610
+ *
611
+ * @param callbackUrl The full callback URL with query parameters
612
+ */
613
+ async handleCallback(callbackUrl) {
614
+ const { code, state, error, errorDescription } = parseOAuthCallback(callbackUrl);
615
+ if (error) {
616
+ this._authFlowResolve?.();
617
+ this._authFlowResolve = null;
618
+ throw new AuthorizationRequiredError(
619
+ errorDescription ?? `OAuth error: ${error}`
620
+ );
621
+ }
622
+ const isValidState = await this.oauthProvider.validateState(state);
623
+ if (!isValidState) {
624
+ this._authFlowResolve?.();
625
+ this._authFlowResolve = null;
626
+ throw new OAuthError(
627
+ "OAuth state validation failed. The state parameter did not match. Retry the authorization flow.",
628
+ "kontext_oauth_state_invalid"
629
+ );
630
+ }
631
+ if (!code) {
632
+ this._authFlowResolve?.();
633
+ this._authFlowResolve = null;
634
+ throw new AuthorizationRequiredError(
635
+ "No authorization code in callback URL"
636
+ );
637
+ }
638
+ try {
639
+ if (!this.transport) {
640
+ this.transport = new StreamableHTTPClientTransport(
641
+ new URL(this.mcpEndpointUrl),
642
+ {
643
+ authProvider: this.oauthProvider
644
+ }
645
+ );
646
+ }
647
+ await this.transport.finishAuth(code);
648
+ const tokens = await this.oauthProvider.tokens();
649
+ if (!tokens?.access_token) {
650
+ throw new AuthorizationRequiredError("Failed to obtain tokens");
651
+ }
652
+ await this.oauthProvider.saveTokens(tokens);
653
+ } finally {
654
+ this._authFlowResolve?.();
655
+ this._authFlowResolve = null;
656
+ }
657
+ }
658
+ /**
659
+ * Disconnect from the server
660
+ */
661
+ async disconnect() {
662
+ try {
663
+ if (this.transport) {
664
+ try {
665
+ await this.transport.terminateSession();
666
+ } catch {
667
+ }
668
+ await this.transport.close();
669
+ }
670
+ } finally {
671
+ this.transport = null;
672
+ this.client = null;
673
+ this._isConnected = false;
674
+ }
675
+ }
676
+ /**
677
+ * Clear stored tokens and require re-authentication
678
+ */
679
+ async clearAuth() {
680
+ await this.oauthProvider.clearAll();
681
+ await this.disconnect();
682
+ }
683
+ /**
684
+ * Check if this URL is an OAuth callback
685
+ *
686
+ * Useful for web apps to detect if the current URL is a callback.
687
+ *
688
+ * @param url The URL to check
689
+ */
690
+ isCallback(url) {
691
+ const urlObj = typeof url === "string" ? new URL(url) : url;
692
+ const redirectUri = new URL(this.config.redirectUri);
693
+ return urlObj.pathname === redirectUri.pathname && (urlObj.searchParams.has("code") || urlObj.searchParams.has("error"));
694
+ }
695
+ /**
696
+ * Ensure we're connected, handling auth if needed
697
+ */
698
+ async ensureConnected() {
699
+ if (this._isConnected && this.client) {
700
+ return;
701
+ }
702
+ if (this._pendingConnect) {
703
+ await this._pendingConnect;
704
+ return;
705
+ }
706
+ this._pendingConnect = this.doConnect();
707
+ try {
708
+ await this._pendingConnect;
709
+ } finally {
710
+ this._pendingConnect = null;
711
+ }
712
+ }
713
+ /**
714
+ * Internal connection logic
715
+ */
716
+ async doConnect(authRetryCount = 0) {
717
+ if (!this.transport) {
718
+ this.transport = new StreamableHTTPClientTransport(
719
+ new URL(this.mcpEndpointUrl),
720
+ {
721
+ authProvider: this.oauthProvider
722
+ }
723
+ );
724
+ }
725
+ const capabilities = {
726
+ tools: {}
727
+ };
728
+ if (this.config.onElicitationUrl) {
729
+ capabilities.elicitation = { url: {} };
730
+ }
731
+ this.client = new Client(
732
+ {
733
+ name: this.config.clientName ?? "kontext-sdk",
734
+ version: this.config.clientVersion ?? "0.0.1"
735
+ },
736
+ { capabilities }
737
+ );
738
+ if (this.config.onElicitationUrl) {
739
+ const onElicitationUrl = this.config.onElicitationUrl;
740
+ this.client.setRequestHandler(ElicitRequestSchema, async (request) => {
741
+ const params = request.params;
742
+ if (params.mode === "url" && "url" in params) {
743
+ await onElicitationUrl({
744
+ url: params.url,
745
+ message: params.message ?? "Action required",
746
+ elicitationId: params.elicitationId ?? "",
747
+ integrationId: params.integrationId,
748
+ integrationName: params.integrationName
749
+ });
750
+ }
751
+ return { action: "accept" };
752
+ });
753
+ this.client.setNotificationHandler(
754
+ ElicitationCompleteNotificationSchema,
755
+ () => {
756
+ }
757
+ );
758
+ }
759
+ try {
760
+ await this.client.connect(this.transport);
761
+ this._isConnected = true;
762
+ } catch (error) {
763
+ if (error instanceof Error && isUnauthorizedError(error)) {
764
+ if (this._pendingAuthFlow) {
765
+ await this._pendingAuthFlow;
766
+ this._pendingAuthFlow = null;
767
+ this.transport = null;
768
+ this.client = null;
769
+ if (authRetryCount >= 1) {
770
+ throw new AuthorizationRequiredError(
771
+ "Authorization completed, but the MCP server still rejected the token. Verify OAuth resource audience and token issuer configuration.",
772
+ { cause: error }
773
+ );
774
+ }
775
+ return this.doConnect(authRetryCount + 1);
776
+ }
777
+ this.transport = null;
778
+ this.client = null;
779
+ throw new AuthorizationRequiredError(
780
+ "Authorization required. Complete the OAuth flow and retry."
781
+ );
782
+ }
783
+ this.transport = null;
784
+ this.client = null;
785
+ if (error instanceof KontextError) throw error;
786
+ throw new KontextError(
787
+ `Failed to connect to MCP server at ${this.mcpEndpointUrl}. ${error instanceof Error ? error.message : String(error)}`,
788
+ "kontext_mcp_connection_failed",
789
+ { cause: error }
790
+ );
791
+ }
792
+ }
793
+ };
794
+
795
+ export { KontextMcp };
796
+ //# sourceMappingURL=index.js.map
797
+ //# sourceMappingURL=index.js.map