@kontext-dev/js-sdk 0.1.1 → 1.0.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.
- package/dist/adapters/ai/index.cjs +135 -58
- package/dist/adapters/ai/index.cjs.map +1 -1
- package/dist/adapters/ai/index.js +135 -58
- package/dist/adapters/ai/index.js.map +1 -1
- package/dist/adapters/cloudflare/index.cjs +28 -70
- package/dist/adapters/cloudflare/index.cjs.map +1 -1
- package/dist/adapters/cloudflare/index.js +28 -70
- package/dist/adapters/cloudflare/index.js.map +1 -1
- package/dist/client/index.cjs +33 -9
- package/dist/client/index.cjs.map +1 -1
- package/dist/client/index.js +33 -9
- package/dist/client/index.js.map +1 -1
- package/dist/index.cjs +42 -9
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +42 -9
- package/dist/index.js.map +1 -1
- package/dist/management/index.cjs.map +1 -1
- package/dist/management/index.d.cts +2 -2
- package/dist/management/index.d.ts +2 -2
- package/dist/management/index.js.map +1 -1
- package/dist/mcp/index.cjs +28 -8
- package/dist/mcp/index.cjs.map +1 -1
- package/dist/mcp/index.d.cts +5 -1
- package/dist/mcp/index.d.ts +5 -1
- package/dist/mcp/index.js +28 -8
- package/dist/mcp/index.js.map +1 -1
- package/dist/oauth/index.cjs.map +1 -1
- package/dist/oauth/index.d.cts +1 -1
- package/dist/oauth/index.d.ts +1 -1
- package/dist/oauth/index.js.map +1 -1
- package/dist/server/index.cjs +9 -0
- package/dist/server/index.cjs.map +1 -1
- package/dist/server/index.d.cts +1 -1
- package/dist/server/index.d.ts +1 -1
- package/dist/server/index.js +9 -0
- package/dist/server/index.js.map +1 -1
- package/dist/{types-CzhnlJHW.d.cts → types-C6ep5fVw.d.cts} +2 -0
- package/dist/{types-CzhnlJHW.d.ts → types-C6ep5fVw.d.ts} +2 -0
- package/package.json +1 -1
package/dist/mcp/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/storage/memory.ts","../../src/storage/types.ts","../../src/errors.ts","../../src/oauth/provider.ts","../../src/mcp/client.ts"],"names":["randomBytes","UrlElicitationRequiredError","StreamableHTTPClientTransport","Client","ElicitRequestSchema","ElicitationCompleteNotificationSchema"],"mappings":";;;;;;;;;;AAWO,IAAM,gBAAN,MAA8C;AAAA,EAC3C,KAAA,uBAAY,GAAA,EAAqB;AAAA,EAEzC,MAAM,QAAW,GAAA,EAAqC;AACpD,IAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,KAAA,CAAM,GAAA,CAAI,GAAG,CAAA;AAChC,IAAA,IAAI,UAAU,MAAA,EAAW;AACvB,MAAA,OAAO,MAAA;AAAA,IACT;AAEA,IAAA,OAAO,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,SAAA,CAAU,KAAK,CAAC,CAAA;AAAA,EACzC;AAAA,EAEA,MAAM,OAAA,CAAW,GAAA,EAAa,KAAA,EAAqC;AACjE,IAAA,IAAI,UAAU,MAAA,EAAW;AACvB,MAAA,IAAA,CAAK,KAAA,CAAM,OAAO,GAAG,CAAA;AAAA,IACvB,CAAA,MAAO;AAEL,MAAA,IAAA,CAAK,KAAA,CAAM,IAAI,GAAA,EAAK,IAAA,CAAK,MAAM,IAAA,CAAK,SAAA,CAAU,KAAK,CAAC,CAAC,CAAA;AAAA,IACvD;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,KAAA,GAAc;AACZ,IAAA,IAAA,CAAK,MAAM,KAAA,EAAM;AAAA,EACnB;AAAA;AAAA;AAAA;AAAA,EAKA,IAAI,IAAA,GAAe;AACjB,IAAA,OAAO,KAAK,KAAA,CAAM,IAAA;AAAA,EACpB;AAAA;AAAA;AAAA;AAAA,EAKA,IAAI,GAAA,EAAsB;AACxB,IAAA,OAAO,IAAA,CAAK,KAAA,CAAM,GAAA,CAAI,GAAG,CAAA;AAAA,EAC3B;AAAA;AAAA;AAAA;AAAA,EAKA,IAAA,GAAiB;AACf,IAAA,OAAO,KAAA,CAA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C,CAAA,CAAA;AAAA,QACpH,+BAAA;AAAA,QACA,EAAE,OAAO,KAAA;AAAM,OACjB;AAAA,IACF;AAAA,EACF;AACF","file":"index.cjs","sourcesContent":["/**\n * In-memory storage implementation\n * Useful for tests, examples, and ephemeral sessions\n */\n\nimport type { KontextStorage } from \"./types.js\";\n\n/**\n * Simple in-memory storage implementation\n * Data is lost when the process exits\n */\nexport class MemoryStorage implements KontextStorage {\n private store = new Map<string, unknown>();\n\n async getJson<T>(key: string): Promise<T | undefined> {\n const value = this.store.get(key);\n if (value === undefined) {\n return undefined;\n }\n // Return a deep copy to prevent mutation\n return JSON.parse(JSON.stringify(value)) as T;\n }\n\n async setJson<T>(key: string, value: T | undefined): Promise<void> {\n if (value === undefined) {\n this.store.delete(key);\n } else {\n // Store a deep copy to prevent mutation\n this.store.set(key, JSON.parse(JSON.stringify(value)));\n }\n }\n\n /**\n * Clear all stored data\n */\n clear(): void {\n this.store.clear();\n }\n\n /**\n * Get the number of stored items\n */\n get size(): number {\n return this.store.size;\n }\n\n /**\n * Check if a key exists\n */\n has(key: string): boolean {\n return this.store.has(key);\n }\n\n /**\n * Get all keys (useful for debugging)\n */\n keys(): string[] {\n return Array.from(this.store.keys());\n }\n}\n","/**\n * Storage interface for persisting SDK state\n */\n\n/**\n * Generic storage interface for the Kontext SDK\n * Implementations can store data in memory, file system, or external services\n */\nexport interface KontextStorage {\n /**\n * Retrieve a JSON value by key\n * @param key Storage key\n * @returns The stored value or undefined if not found\n */\n getJson<T>(key: string): Promise<T | undefined>;\n\n /**\n * Store a JSON value by key\n * @param key Storage key\n * @param value The value to store, or undefined to delete\n */\n setJson<T>(key: string, value: T | undefined): Promise<void>;\n}\n\n/**\n * Storage key namespacing helper\n * Creates namespaced keys based on application client ID and optional session key\n */\nexport function createStorageKey(\n applicationClientId: string,\n sessionKey: string | undefined,\n ...parts: string[]\n): string {\n const namespace = sessionKey\n ? `kontext:${applicationClientId}:${sessionKey}`\n : `kontext:${applicationClientId}`;\n return [namespace, ...parts].join(\":\");\n}\n\n/**\n * Storage keys used by the SDK\n */\nexport const StorageKeys = {\n // Existing keys\n TOKENS: \"tokens\",\n CODE_VERIFIER: \"code_verifier\",\n STATE: \"state\",\n CLIENT_INFO: \"client_info\",\n\n // Pattern B (RFC 8693 Token Exchange) keys\n /** Identity tokens (no audience) */\n IDENTITY_TOKENS: \"identity_tokens\",\n /** Prefix for resource-scoped tokens */\n RESOURCE_TOKENS: \"resource_tokens\",\n} as const;\n\n/**\n * Create a storage key for a resource-scoped token\n *\n * @param resource The resource identifier (e.g., \"mcp-gateway\")\n * @returns Storage key for the resource token\n *\n * @example\n * ```typescript\n * const key = resourceTokenKey('mcp-gateway');\n * // Returns: 'resource_tokens:mcp-gateway'\n * ```\n */\nexport function resourceTokenKey(resource: string): string {\n return `${StorageKeys.RESOURCE_TOKENS}:${resource}`;\n}\n","/**\n * Typed error classes for the Kontext SDK.\n *\n * Every error has a `kontext_` prefixed code, an auto-generated docsUrl,\n * and a `kontextError` brand for type narrowing without instanceof.\n *\n * @packageDocumentation\n */\n\n// ============================================================================\n// Base\n// ============================================================================\n\n/**\n * Base error class for all Kontext SDK errors.\n *\n * @example\n * ```typescript\n * import { isKontextError } from '@kontext-dev/js-sdk';\n *\n * try {\n * await client.connect();\n * } catch (err) {\n * if (isKontextError(err)) {\n * console.log(err.code); // \"kontext_authorization_required\"\n * console.log(err.docsUrl); // \"https://docs.kontext.dev/errors/kontext_authorization_required\"\n * }\n * }\n * ```\n */\nexport class KontextError extends Error {\n /** Brand field for type narrowing without instanceof */\n readonly kontextError = true as const;\n\n /** Machine-readable error code, always prefixed with `kontext_` */\n readonly code: string;\n\n /** HTTP status code when applicable */\n readonly statusCode?: number;\n\n /** Auto-generated link to error documentation */\n readonly docsUrl: string;\n\n /** Server request ID for debugging / support escalation */\n readonly requestId?: string;\n\n /** Contextual metadata bag (integration IDs, param names, etc.) */\n readonly meta: Record<string, unknown>;\n\n constructor(\n message: string,\n code: string,\n options?: {\n statusCode?: number;\n requestId?: string;\n meta?: Record<string, unknown>;\n cause?: unknown;\n },\n ) {\n super(message, { cause: options?.cause });\n this.name = \"KontextError\";\n this.code = code;\n this.statusCode = options?.statusCode;\n this.requestId = options?.requestId;\n this.meta = options?.meta ?? {};\n this.docsUrl = `https://docs.kontext.dev/errors/${code}`;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n toJSON(): Record<string, unknown> {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n statusCode: this.statusCode,\n docsUrl: this.docsUrl,\n requestId: this.requestId,\n meta: Object.keys(this.meta).length > 0 ? this.meta : undefined,\n };\n }\n\n override toString(): string {\n const parts = [`[${this.code}] ${this.message}`];\n if (this.docsUrl) parts.push(`Docs: ${this.docsUrl}`);\n if (this.requestId) parts.push(`Request ID: ${this.requestId}`);\n return parts.join(\"\\n\");\n }\n}\n\n// ============================================================================\n// Type guard\n// ============================================================================\n\n/**\n * Check if an error is a KontextError without instanceof.\n * Works across package versions and bundler deduplication.\n */\nexport function isKontextError(err: unknown): err is KontextError {\n return (\n typeof err === \"object\" &&\n err !== null &&\n (err as Record<string, unknown>).kontextError === true\n );\n}\n\n// ============================================================================\n// Auth errors\n// ============================================================================\n\n/**\n * Thrown when authentication is required but no valid credentials are available.\n */\nexport class AuthorizationRequiredError extends KontextError {\n readonly authorizationUrl?: string;\n\n constructor(\n message = \"Authorization required. Complete the OAuth flow to continue.\",\n options?: {\n authorizationUrl?: string;\n requestId?: string;\n meta?: Record<string, unknown>;\n cause?: unknown;\n },\n ) {\n super(message, \"kontext_authorization_required\", {\n statusCode: 401,\n ...options,\n });\n this.name = \"AuthorizationRequiredError\";\n this.authorizationUrl = options?.authorizationUrl;\n }\n}\n\n// ============================================================================\n// OAuth errors\n// ============================================================================\n\n/**\n * Thrown when an OAuth flow fails — state validation, token exchange,\n * missing code verifier, or provider errors.\n */\nexport class OAuthError extends KontextError {\n readonly errorCode?: string;\n readonly errorDescription?: string;\n\n constructor(\n message: string,\n code: string,\n options?: {\n statusCode?: number;\n errorCode?: string;\n errorDescription?: string;\n requestId?: string;\n meta?: Record<string, unknown>;\n cause?: unknown;\n },\n ) {\n super(message, code, {\n statusCode: options?.statusCode ?? 400,\n ...options,\n });\n this.name = \"OAuthError\";\n this.errorCode = options?.errorCode;\n this.errorDescription = options?.errorDescription;\n }\n}\n\n// ============================================================================\n// Integration errors\n// ============================================================================\n\n/**\n * Thrown when an integration connection is required before a tool can be used.\n */\nexport class IntegrationConnectionRequiredError extends KontextError {\n readonly integrationId: string;\n readonly integrationName?: string;\n readonly connectUrl?: string;\n\n constructor(\n integrationId: string,\n options?: {\n integrationName?: string;\n connectUrl?: string;\n message?: string;\n requestId?: string;\n meta?: Record<string, unknown>;\n cause?: unknown;\n },\n ) {\n super(\n options?.message ??\n `Connection to integration \"${integrationId}\" is required. Visit the connect URL to authorize.`,\n \"kontext_integration_connection_required\",\n { statusCode: 403, ...options },\n );\n this.name = \"IntegrationConnectionRequiredError\";\n this.integrationId = integrationId;\n this.integrationName = options?.integrationName;\n this.connectUrl = options?.connectUrl;\n }\n}\n\n// ============================================================================\n// Config errors (NEW — replaces all plain Error config throws)\n// ============================================================================\n\n/**\n * Thrown when SDK configuration is invalid or missing.\n * These are deterministic errors caught at initialization time.\n */\nexport class ConfigError extends KontextError {\n constructor(\n message: string,\n code: string,\n options?: {\n meta?: Record<string, unknown>;\n cause?: unknown;\n },\n ) {\n super(message, code, options);\n this.name = \"ConfigError\";\n }\n}\n\n// ============================================================================\n// Network errors\n// ============================================================================\n\n/**\n * Thrown when there is a network or connection error.\n */\nexport class NetworkError extends KontextError {\n constructor(\n message = \"Network error. Check your internet connection and that the server is reachable.\",\n options?: {\n cause?: unknown;\n requestId?: string;\n meta?: Record<string, unknown>;\n },\n ) {\n super(message, \"kontext_network_error\", options);\n this.name = \"NetworkError\";\n }\n}\n\n// ============================================================================\n// HTTP response errors (differentiated by code)\n// ============================================================================\n\n/**\n * Thrown when the server returns an HTTP error.\n * Use `error.code` to distinguish between specific error types.\n */\nexport class HttpError extends KontextError {\n readonly retryAfter?: number;\n readonly validationErrors?: Array<{ field: string; message: string }>;\n\n constructor(\n message: string,\n code: string,\n options?: {\n statusCode?: number;\n retryAfter?: number;\n validationErrors?: Array<{ field: string; message: string }>;\n requestId?: string;\n meta?: Record<string, unknown>;\n cause?: unknown;\n },\n ) {\n super(message, code, {\n statusCode: options?.statusCode,\n ...options,\n });\n this.name = \"HttpError\";\n this.retryAfter = options?.retryAfter;\n this.validationErrors = options?.validationErrors;\n }\n}\n\n// ============================================================================\n// Network error detection (used by translateError)\n// ============================================================================\n\n/**\n * Safely access arbitrary properties on an error object.\n * Errors in JS frequently carry extra properties (code, statusCode, etc.)\n * that aren't part of the Error interface. This avoids `as unknown as` casts.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction errorProps(err: Error): Record<string, any> {\n return err;\n}\n\nconst NETWORK_ERROR_CODES = new Set([\n \"ECONNREFUSED\",\n \"ENOTFOUND\",\n \"ETIMEDOUT\",\n \"ECONNRESET\",\n \"ECONNABORTED\",\n \"EPIPE\",\n \"UND_ERR_CONNECT_TIMEOUT\",\n]);\n\n/**\n * Detect network errors structurally rather than by string matching.\n * Checks Node.js system error codes on the error and its cause.\n */\nexport function isNetworkError(err: Error): boolean {\n if (err.name === \"AbortError\") return true;\n\n const props = errorProps(err);\n const sysCode = props.code as string | undefined;\n if (typeof sysCode === \"string\" && NETWORK_ERROR_CODES.has(sysCode))\n return true;\n\n // fetch() throws TypeError — only classify as network error when cause\n // indicates a system-level failure\n if (err.name === \"TypeError\" && err.cause instanceof Error) {\n const causeCode = errorProps(err.cause).code;\n if (typeof causeCode === \"string\" && NETWORK_ERROR_CODES.has(causeCode))\n return true;\n }\n\n return false;\n}\n\n/**\n * Detect unauthorized errors structurally.\n * Checks status code and numeric code rather than string matching on name.\n */\nexport function isUnauthorizedError(err: Error): boolean {\n const props = errorProps(err);\n\n // Check HTTP status code (most reliable)\n if (props.statusCode === 401 || props.status === 401) return true;\n\n // Check MCP SDK UnauthorizedError by name (last resort, but needed for\n // MCP SDK errors which don't set statusCode)\n if (err.name === \"UnauthorizedError\") return true;\n if (err.message === \"Unauthorized\") return true;\n\n return false;\n}\n\n// ============================================================================\n// Elicitation types\n// ============================================================================\n\nexport interface ElicitationEntry {\n readonly url: string;\n readonly message: string;\n readonly elicitationId: string;\n readonly integrationId?: string;\n readonly integrationName?: string;\n}\n\n// ============================================================================\n// HTTP error parsing\n// ============================================================================\n\n/**\n * Parse an HTTP response into an appropriate error.\n */\nexport function parseHttpError(\n statusCode: number,\n body?: unknown,\n): KontextError {\n const message =\n typeof body === \"object\" && body !== null && \"message\" in body\n ? String((body as { message: unknown }).message)\n : `HTTP ${statusCode}`;\n\n const errorCode =\n typeof body === \"object\" && body !== null && \"code\" in body\n ? String((body as { code: unknown }).code)\n : undefined;\n\n switch (statusCode) {\n case 400:\n if (\n typeof body === \"object\" &&\n body !== null &&\n \"errors\" in body &&\n Array.isArray((body as { errors: unknown }).errors)\n ) {\n return new HttpError(message, \"kontext_validation_error\", {\n statusCode: 400,\n validationErrors: (\n body as { errors: Array<{ field: string; message: string }> }\n ).errors,\n });\n }\n return new KontextError(message, errorCode ?? \"kontext_bad_request\", {\n statusCode: 400,\n });\n\n case 401:\n return new AuthorizationRequiredError(message);\n\n case 403:\n if (errorCode === \"INTEGRATION_CONNECTION_REQUIRED\") {\n const details = body as {\n integrationId?: string;\n integrationName?: string;\n connectUrl?: string;\n };\n return new IntegrationConnectionRequiredError(\n details.integrationId ?? \"unknown\",\n {\n integrationName: details.integrationName,\n connectUrl: details.connectUrl,\n message,\n },\n );\n }\n return new HttpError(message, \"kontext_policy_denied\", {\n statusCode: 403,\n meta: { policy: (body as Record<string, unknown>)?.policy },\n });\n\n case 404:\n return new HttpError(message, \"kontext_not_found\", { statusCode: 404 });\n\n case 429: {\n const retryAfter =\n typeof body === \"object\" && body !== null && \"retryAfter\" in body\n ? Number((body as { retryAfter: unknown }).retryAfter)\n : undefined;\n return new HttpError(\n retryAfter\n ? `Rate limit exceeded. Retry after ${retryAfter} seconds.`\n : \"Rate limit exceeded. Wait and retry.\",\n \"kontext_rate_limited\",\n { statusCode: 429, retryAfter },\n );\n }\n\n default:\n if (statusCode >= 500) {\n return new HttpError(\n `Server error (HTTP ${statusCode}): ${message}`,\n \"kontext_server_error\",\n { statusCode },\n );\n }\n return new KontextError(message, errorCode ?? \"kontext_unknown_error\", {\n statusCode,\n });\n }\n}\n","/**\n * KontextOAuthProvider - Implements OAuthClientProvider from @modelcontextprotocol/sdk\n *\n * This provider handles the OAuth 2.0 Authorization Code + PKCE flow\n * for authenticating MCP clients with the Kontext Gateway.\n */\n\nimport type { OAuthClientProvider } from \"@modelcontextprotocol/sdk/client/auth.js\";\nimport type {\n OAuthClientMetadata,\n OAuthClientInformationMixed,\n OAuthTokens,\n} from \"@modelcontextprotocol/sdk/shared/auth.js\";\nimport { randomBytes } from \"node:crypto\";\nimport type { KontextStorage } from \"../storage/types.js\";\nimport {\n createStorageKey,\n StorageKeys,\n resourceTokenKey,\n} from \"../storage/types.js\";\nimport { OAuthError } from \"../errors.js\";\n\nexport interface KontextOAuthProviderConfig {\n /**\n * Application OAuth client ID from Kontext\n */\n clientId: string;\n\n /**\n * Redirect URI for OAuth callback\n * Must match one of the registered redirect URIs for the application\n */\n redirectUri: string;\n\n /**\n * Storage implementation for persisting tokens and PKCE state\n */\n storage: KontextStorage;\n\n /**\n * Optional session key for namespacing storage\n * Useful when multiple users/sessions share the same storage\n */\n sessionKey?: string;\n\n /**\n * Optional client name for OAuth metadata\n */\n clientName?: string;\n\n /**\n * Callback to redirect the user agent to the authorization URL\n * This is called when authorization is required\n *\n * @param url The authorization URL to redirect to\n */\n onRedirectToAuthorization: (url: URL) => void | Promise<void>;\n}\n\n/**\n * OAuth provider implementation for Kontext MCP clients\n *\n * Implements the OAuthClientProvider interface from @modelcontextprotocol/sdk\n * to handle Authorization Code + PKCE authentication flow.\n *\n * @example\n * ```typescript\n * const storage = new MemoryStorage();\n * const provider = new KontextOAuthProvider({\n * clientId: 'your-client-id',\n * redirectUri: 'http://localhost:3000/callback',\n * storage,\n * onRedirectToAuthorization: (url) => {\n * // Open browser or redirect\n * window.location.href = url.toString();\n * },\n * });\n * ```\n */\nexport class KontextOAuthProvider implements OAuthClientProvider {\n private readonly config: KontextOAuthProviderConfig;\n private readonly storagePrefix: string;\n private pendingState: string | null = null;\n private readonly expiryBufferMs = 60 * 1000;\n\n constructor(config: KontextOAuthProviderConfig) {\n this.config = config;\n this.storagePrefix = createStorageKey(config.clientId, config.sessionKey);\n }\n\n /**\n * The redirect URL for OAuth callbacks\n */\n get redirectUrl(): string | URL {\n return this.config.redirectUri;\n }\n\n /**\n * OAuth client metadata\n */\n get clientMetadata(): OAuthClientMetadata {\n return {\n redirect_uris: [this.config.redirectUri],\n client_name: this.config.clientName,\n grant_types: [\"authorization_code\", \"refresh_token\"],\n response_types: [\"code\"],\n token_endpoint_auth_method: \"none\", // Public client\n };\n }\n\n /**\n * Generate a random state parameter for OAuth CSRF protection\n */\n state(): string {\n // Generate a cryptographically secure random string\n const array = new Uint8Array(32);\n if (globalThis.crypto?.getRandomValues) {\n globalThis.crypto.getRandomValues(array);\n } else {\n array.set(randomBytes(32));\n }\n const state = Array.from(array, (byte) =>\n byte.toString(16).padStart(2, \"0\"),\n ).join(\"\");\n this.pendingState = state;\n void this.config.storage.setJson(\n this.getStorageKey(StorageKeys.STATE),\n state,\n );\n return state;\n }\n\n /**\n * Returns the client information (client_id)\n * Since we're a public client with pre-registered credentials,\n * we don't use dynamic client registration.\n */\n async clientInformation(): Promise<OAuthClientInformationMixed | undefined> {\n return {\n client_id: this.config.clientId,\n };\n }\n\n /**\n * Load stored OAuth tokens\n */\n async tokens(): Promise<OAuthTokens | undefined> {\n const key = this.getStorageKey(StorageKeys.TOKENS);\n return this.config.storage.getJson<OAuthTokens>(key);\n }\n\n /**\n * Save OAuth tokens after successful authorization\n */\n async saveTokens(tokens: OAuthTokens): Promise<void> {\n const key = this.getStorageKey(StorageKeys.TOKENS);\n await this.config.storage.setJson(key, this.withIssuedAt(tokens));\n }\n\n /**\n * Redirect the user agent to the authorization URL\n */\n async redirectToAuthorization(authorizationUrl: URL): Promise<void> {\n await this.config.onRedirectToAuthorization(authorizationUrl);\n }\n\n /**\n * Save the PKCE code verifier before redirecting to authorization\n */\n async saveCodeVerifier(codeVerifier: string): Promise<void> {\n const key = this.getStorageKey(StorageKeys.CODE_VERIFIER);\n await this.config.storage.setJson(key, codeVerifier);\n }\n\n /**\n * Load the PKCE code verifier for token exchange\n */\n async codeVerifier(): Promise<string> {\n const key = this.getStorageKey(StorageKeys.CODE_VERIFIER);\n const verifier = await this.config.storage.getJson<string>(key);\n if (!verifier) {\n throw new OAuthError(\n \"No PKCE code verifier found in storage. The OAuth flow may have expired or storage was cleared. Restart the auth flow.\",\n \"kontext_oauth_code_verifier_missing\",\n );\n }\n return verifier;\n }\n\n /**\n * Invalidate stored credentials\n */\n async invalidateCredentials(\n scope: \"all\" | \"client\" | \"tokens\" | \"verifier\",\n ): Promise<void> {\n if (scope === \"all\" || scope === \"tokens\") {\n const tokensKey = this.getStorageKey(StorageKeys.TOKENS);\n await this.config.storage.setJson(tokensKey, undefined);\n const identityKey = this.getStorageKey(StorageKeys.IDENTITY_TOKENS);\n await this.config.storage.setJson(identityKey, undefined);\n }\n if (scope === \"all\" || scope === \"verifier\") {\n const verifierKey = this.getStorageKey(StorageKeys.CODE_VERIFIER);\n await this.config.storage.setJson(verifierKey, undefined);\n }\n if (scope === \"all\") {\n this.pendingState = null;\n const stateKey = this.getStorageKey(StorageKeys.STATE);\n await this.config.storage.setJson(stateKey, undefined);\n }\n // 'client' scope is a no-op since we use pre-registered client info\n }\n\n /**\n * Clear all stored state (tokens, verifier, etc.)\n * Call this to force re-authentication\n */\n async clearAll(): Promise<void> {\n await this.invalidateCredentials(\"all\");\n }\n\n /**\n * Check if we have valid (non-expired) tokens\n */\n async hasValidTokens(): Promise<boolean> {\n const storedTokens = await this.tokens();\n return this.isTokenValid(storedTokens);\n }\n\n // ==========================================================================\n // Pattern B: Identity and Resource Token Management (RFC 8693)\n // ==========================================================================\n\n /**\n * Save identity tokens (no audience)\n * These are the tokens obtained from the initial OAuth flow before token exchange.\n */\n async saveIdentityTokens(tokens: OAuthTokens): Promise<void> {\n const key = this.getStorageKey(StorageKeys.IDENTITY_TOKENS);\n await this.config.storage.setJson(key, this.withIssuedAt(tokens));\n }\n\n /**\n * Load identity tokens\n * Returns the identity tokens obtained from the initial OAuth flow.\n */\n async identityTokens(): Promise<OAuthTokens | undefined> {\n const key = this.getStorageKey(StorageKeys.IDENTITY_TOKENS);\n return this.config.storage.getJson<OAuthTokens>(key);\n }\n\n /**\n * Save resource-scoped tokens for a specific resource\n *\n * @param resource The resource identifier (e.g., \"mcp-gateway\")\n * @param tokens The resource-scoped tokens\n */\n async saveResourceTokens(\n resource: string,\n tokens: OAuthTokens,\n ): Promise<void> {\n const key = this.getStorageKey(resourceTokenKey(resource));\n await this.config.storage.setJson(key, this.withIssuedAt(tokens));\n }\n\n /**\n * Load resource-scoped tokens for a specific resource\n *\n * @param resource The resource identifier (e.g., \"mcp-gateway\")\n * @returns The resource-scoped tokens, or undefined if not found\n */\n async resourceTokens(resource: string): Promise<OAuthTokens | undefined> {\n const key = this.getStorageKey(resourceTokenKey(resource));\n return this.config.storage.getJson<OAuthTokens>(key);\n }\n\n /**\n * Clear resource tokens for a specific resource\n *\n * @param resource The resource identifier (e.g., \"mcp-gateway\")\n */\n async clearResourceTokens(resource: string): Promise<void> {\n const key = this.getStorageKey(resourceTokenKey(resource));\n await this.config.storage.setJson(key, undefined);\n }\n\n /**\n * Check if we have valid identity tokens\n */\n async hasValidIdentityTokens(): Promise<boolean> {\n const tokens = await this.identityTokens();\n return this.isTokenValid(tokens);\n }\n\n /**\n * Check if we have valid resource tokens for a specific resource\n *\n * @param resource The resource identifier\n */\n async hasValidResourceTokens(resource: string): Promise<boolean> {\n const tokens = await this.resourceTokens(resource);\n return this.isTokenValid(tokens);\n }\n\n async validateState(state?: string): Promise<boolean> {\n if (!state) {\n return false;\n }\n\n const key = this.getStorageKey(StorageKeys.STATE);\n const storedState =\n this.pendingState ?? (await this.config.storage.getJson<string>(key));\n const isValid = storedState === state;\n\n if (isValid) {\n this.pendingState = null;\n await this.config.storage.setJson(key, undefined);\n }\n\n return isValid;\n }\n\n private withIssuedAt(\n tokens: OAuthTokens,\n ): OAuthTokens & { issued_at?: number } {\n if (!tokens.expires_in) {\n return tokens;\n }\n return { ...tokens, issued_at: Date.now() };\n }\n\n private isTokenValid(tokens?: OAuthTokens): boolean {\n if (!tokens?.access_token) {\n return false;\n }\n\n if (!tokens.expires_in) {\n return true;\n }\n\n const issuedAt = (tokens as OAuthTokens & { issued_at?: number }).issued_at;\n if (!issuedAt) {\n return true;\n }\n\n const expiresAt = issuedAt + tokens.expires_in * 1000;\n return Date.now() < expiresAt - this.expiryBufferMs;\n }\n\n private getStorageKey(key: string): string {\n return `${this.storagePrefix}:${key}`;\n }\n}\n\n/**\n * Parse an OAuth callback URL and extract the authorization code and state\n *\n * @param callbackUrl The full callback URL with query parameters\n * @returns The authorization code and state, or error details\n */\nexport function parseOAuthCallback(callbackUrl: string | URL): {\n code?: string;\n state?: string;\n error?: string;\n errorDescription?: string;\n} {\n const url =\n typeof callbackUrl === \"string\" ? new URL(callbackUrl) : callbackUrl;\n const params = url.searchParams;\n\n const error = params.get(\"error\");\n if (error) {\n return {\n error,\n errorDescription: params.get(\"error_description\") ?? undefined,\n };\n }\n\n return {\n code: params.get(\"code\") ?? undefined,\n state: params.get(\"state\") ?? undefined,\n };\n}\n","/**\n * KontextMcp - Runtime client for MCP connections via Kontext\n *\n * This is the main entrypoint for MCP clients using Kontext.\n * It wraps the MCP SDK's Client and StreamableHTTPClientTransport\n * with Kontext-specific OAuth handling.\n *\n * Authentication is handled transparently:\n * 1. First API call triggers OAuth if needed\n * 2. Connection is established lazily\n *\n * All MCP servers (gateway and custom) are treated identically —\n * the auth code flow produces resource-scoped tokens directly.\n *\n * @example\n * ```typescript\n * import { KontextMcp } from '@kontext-dev/js-sdk';\n *\n * const kontext = new KontextMcp({\n * clientId: 'your-client-id',\n * redirectUri: 'http://localhost:3000/callback',\n * onAuthRequired: async (url) => {\n * // CLI: open browser, wait for callback, return URL\n * // Web: redirect (return nothing, handle callback separately)\n * open(url.toString());\n * return await waitForCallback();\n * },\n * });\n *\n * // Just use it - auth happens automatically\n * const tools = await kontext.listTools();\n * const result = await kontext.callTool('tool_name', { arg: 'value' });\n * ```\n */\n\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport {\n type Tool,\n type CallToolResult,\n UrlElicitationRequiredError,\n ElicitRequestSchema,\n ElicitationCompleteNotificationSchema,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type { KontextStorage } from \"../storage/types.js\";\nimport { MemoryStorage } from \"../storage/memory.js\";\nimport { KontextOAuthProvider, parseOAuthCallback } from \"../oauth/provider.js\";\nimport {\n AuthorizationRequiredError,\n OAuthError,\n KontextError,\n isUnauthorizedError,\n} from \"../errors.js\";\nimport type { ElicitationEntry } from \"../errors.js\";\n\n/**\n * Default Kontext API server URL\n */\nconst DEFAULT_SERVER = \"https://api.kontext.dev\";\n\nexport function normalizeKontextServerUrl(server: string): string {\n let url = server.replace(/\\/$/, \"\");\n\n // Be forgiving if callers pass a versioned API URL or MCP URL instead of the root origin.\n // Data-plane routes (/mcp, /oauth2, /.well-known) are intentionally outside /api/v1.\n url = url.replace(/\\/api\\/v1\\/?$/, \"\").replace(/\\/mcp\\/?$/, \"\");\n url = url.replace(/\\/$/, \"\");\n\n return url;\n}\n\nexport interface KontextMcpConfig {\n /**\n * Application OAuth client ID\n */\n clientId: string;\n\n /**\n * Full URL of the MCP server endpoint.\n * When provided, the client connects directly to this URL.\n *\n * @example \"https://my-server.com/mcp\"\n */\n url?: string;\n\n /**\n * Base URL for the Kontext server.\n * Defaults to \"https://api.kontext.dev\".\n * Only override for local development or self-hosted instances.\n */\n server?: string;\n\n /**\n * Redirect URI for OAuth callback\n * Must match one of the registered redirect URIs for the application\n */\n redirectUri: string;\n\n /**\n * Storage implementation for persisting tokens\n * Defaults to MemoryStorage if not provided\n */\n storage?: KontextStorage;\n\n /**\n * Optional session key for namespacing storage\n * Useful when multiple users/sessions share the same storage\n * Defaults to \"default\"\n */\n sessionKey?: string;\n\n /**\n * Client name for identification in MCP protocol\n */\n clientName?: string;\n\n /**\n * Client version for identification in MCP protocol\n */\n clientVersion?: string;\n\n /**\n * Callback invoked when OAuth authorization is required.\n *\n * For CLI/Desktop apps:\n * Open the browser, wait for the callback, and return the callback URL.\n * The SDK will extract the code and complete the flow.\n *\n * For Web apps:\n * Redirect to the URL (return nothing). After redirect back,\n * call `handleCallback(url)` on a fresh instance.\n *\n * @param url The authorization URL to open/redirect to\n * @returns The callback URL (CLI/Desktop) or void/Promise<void> (Web)\n */\n onAuthRequired: (\n url: URL,\n ) => string | URL | void | Promise<string | URL | void>;\n\n /**\n * Callback invoked when the server requests URL elicitation (MCP spec -32042).\n * This is the protocol-native way for servers to ask the user to visit a URL\n * (e.g., to connect an OAuth integration).\n *\n * When provided, the client declares `elicitation: { url: {} }` capability.\n */\n onElicitationUrl?: (entry: ElicitationEntry) => void | Promise<void>;\n}\n\nexport type RuntimeIntegrationCategory =\n | \"gateway_remote_mcp\"\n | \"internal_mcp_credentials\";\n\nexport type RuntimeIntegrationConnectType = \"oauth\" | \"credentials\" | \"none\";\n\nexport interface RuntimeIntegrationRecord {\n id: string;\n name: string;\n url: string;\n category: RuntimeIntegrationCategory;\n connectType: RuntimeIntegrationConnectType;\n authMode?: \"oauth\" | \"user_token\" | \"server_token\" | \"none\";\n credentialSchema?: unknown;\n requiresOauth?: boolean;\n connection?: {\n connected: boolean;\n status: \"connected\" | \"disconnected\";\n expiresAt?: string;\n displayName?: string;\n };\n}\n\n/**\n * Kontext MCP runtime client\n *\n * Provides a simplified interface for connecting to any MCP server\n * and interacting with tools. Authentication is handled automatically.\n */\nexport class KontextMcp {\n private readonly config: KontextMcpConfig;\n private readonly storage: KontextStorage;\n private readonly oauthProvider: KontextOAuthProvider;\n private transport: StreamableHTTPClientTransport | null = null;\n private client: Client | null = null;\n private _isConnected = false;\n private _pendingConnect: Promise<void> | null = null;\n private _pendingAuthFlow: Promise<void> | null = null;\n private _authFlowResolve: (() => void) | null = null;\n\n constructor(config: KontextMcpConfig) {\n this.config = config;\n this.storage = config.storage ?? new MemoryStorage();\n\n this.oauthProvider = new KontextOAuthProvider({\n clientId: config.clientId,\n redirectUri: config.redirectUri,\n storage: this.storage,\n sessionKey: config.sessionKey ?? \"default\",\n clientName: config.clientName,\n onRedirectToAuthorization: async (url) => {\n // Create a promise that resolves when auth completes\n this._pendingAuthFlow = new Promise<void>((resolve) => {\n this._authFlowResolve = resolve;\n });\n\n // Delegate to user's callback\n const result = await config.onAuthRequired(url);\n if (result) {\n // User returned a callback URL - complete the flow\n await this.handleCallback(result);\n }\n // If no result, user redirected (web app) - they'll call handleCallback separately\n },\n });\n }\n\n /**\n * Check if we're currently connected\n */\n get isConnected(): boolean {\n return this._isConnected;\n }\n\n /**\n * Get the underlying MCP client for advanced usage\n */\n get mcpClient(): Client | null {\n return this.client;\n }\n\n /**\n * Get the session ID from the transport\n */\n get sessionId(): string | undefined {\n return this.transport?.sessionId;\n }\n\n /**\n * Get the server base URL\n */\n private get serverUrl(): string {\n return normalizeKontextServerUrl(this.config.server ?? DEFAULT_SERVER);\n }\n\n /**\n * Get the MCP endpoint URL.\n * When `url` is provided, use it directly. Otherwise derive from server.\n */\n private get mcpEndpointUrl(): string {\n return this.config.url ?? `${this.serverUrl}/mcp`;\n }\n\n /**\n * List available tools from the server\n *\n * This will automatically handle authentication if needed.\n */\n async listTools(): Promise<Tool[]> {\n await this.ensureConnected();\n const response = await this.client!.listTools();\n return response.tools;\n }\n\n /**\n * Call a tool\n *\n * This will automatically handle authentication if needed.\n *\n * @param name The tool name\n * @param args The tool arguments\n */\n async callTool(\n name: string,\n args?: Record<string, unknown>,\n ): Promise<CallToolResult> {\n await this.ensureConnected();\n try {\n const result = await this.client!.callTool({\n name,\n arguments: args,\n });\n return result as CallToolResult;\n } catch (error) {\n // Handle error-based URL elicitation (MCP -32042)\n if (\n error instanceof UrlElicitationRequiredError &&\n this.config.onElicitationUrl\n ) {\n for (const elicitation of error.elicitations) {\n await this.config.onElicitationUrl({\n url: elicitation.url,\n message: elicitation.message ?? \"Action required\",\n elicitationId: elicitation.elicitationId ?? \"\",\n integrationId: (elicitation as Record<string, unknown>)\n .integrationId as string | undefined,\n integrationName: (elicitation as Record<string, unknown>)\n .integrationName as string | undefined,\n });\n }\n }\n throw error;\n }\n }\n\n /**\n * Create a connect session for the hosted connect UI.\n *\n * Returns a URL that can be opened in a browser to let the user\n * connect integrations proactively (before hitting -32042 errors).\n */\n async createConnectSession(): Promise<{\n connectUrl: string;\n sessionId: string;\n expiresAt: string;\n }> {\n const tokens = await this.oauthProvider.tokens();\n if (!tokens?.access_token) {\n throw new AuthorizationRequiredError(\n \"Authorization required. Complete the OAuth flow first.\",\n );\n }\n\n const response = await fetch(`${this.serverUrl}/mcp/connect-session`, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${tokens.access_token}`,\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (response.status === 401) {\n throw new AuthorizationRequiredError(\n \"Access token expired or invalid. Re-authenticate and retry.\",\n );\n }\n\n if (!response.ok) {\n throw new KontextError(\n `Failed to create connect session: HTTP ${response.status}`,\n \"kontext_connect_session_failed\",\n { statusCode: response.status },\n );\n }\n\n return (await response.json()) as {\n connectUrl: string;\n sessionId: string;\n expiresAt: string;\n };\n }\n\n /**\n * List integrations attached to the current application/runtime identity.\n *\n * This is used by higher-level orchestrators to discover mixed integration\n * topologies (gateway + internal credential integrations).\n */\n async listRuntimeIntegrations(): Promise<RuntimeIntegrationRecord[]> {\n const tokens = await this.oauthProvider.tokens();\n if (!tokens?.access_token) {\n throw new AuthorizationRequiredError(\n \"Authorization required. Complete the OAuth flow first.\",\n );\n }\n\n const response = await fetch(`${this.serverUrl}/mcp/integrations`, {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${tokens.access_token}`,\n },\n });\n\n if (response.status === 401) {\n throw new AuthorizationRequiredError(\n \"Access token expired or invalid. Re-authenticate and retry.\",\n );\n }\n\n if (!response.ok) {\n throw new KontextError(\n `Failed to list runtime integrations: HTTP ${response.status}`,\n \"kontext_runtime_integrations_failed\",\n { statusCode: response.status },\n );\n }\n\n const payload = (await response.json()) as {\n items?: Array<Record<string, unknown>>;\n };\n const items = Array.isArray(payload?.items) ? payload.items : [];\n\n return items\n .map((item): RuntimeIntegrationRecord | null => {\n const id = typeof item.id === \"string\" ? item.id : \"\";\n const name = typeof item.name === \"string\" ? item.name : id;\n const url = typeof item.url === \"string\" ? item.url : \"\";\n if (!id || !url) return null;\n\n const category =\n item.category === \"internal_mcp_credentials\"\n ? \"internal_mcp_credentials\"\n : \"gateway_remote_mcp\";\n const connectType =\n item.connectType === \"credentials\" ||\n item.connectType === \"oauth\" ||\n item.connectType === \"none\"\n ? item.connectType\n : category === \"internal_mcp_credentials\"\n ? \"credentials\"\n : item.authMode === \"oauth\"\n ? \"oauth\"\n : \"none\";\n\n const rawConnection =\n item.connection && typeof item.connection === \"object\"\n ? (item.connection as Record<string, unknown>)\n : undefined;\n const connected =\n rawConnection && typeof rawConnection.connected === \"boolean\"\n ? rawConnection.connected\n : false;\n const status =\n rawConnection?.status === \"connected\" ? \"connected\" : \"disconnected\";\n\n return {\n id,\n name,\n url,\n category,\n connectType,\n authMode:\n item.authMode === \"oauth\" ||\n item.authMode === \"user_token\" ||\n item.authMode === \"server_token\" ||\n item.authMode === \"none\"\n ? item.authMode\n : undefined,\n credentialSchema: item.credentialSchema,\n requiresOauth:\n typeof item.requiresOauth === \"boolean\"\n ? item.requiresOauth\n : undefined,\n connection: rawConnection\n ? {\n connected,\n status,\n expiresAt:\n typeof rawConnection.expiresAt === \"string\"\n ? rawConnection.expiresAt\n : undefined,\n displayName:\n typeof rawConnection.displayName === \"string\"\n ? rawConnection.displayName\n : undefined,\n }\n : undefined,\n };\n })\n .filter((item): item is RuntimeIntegrationRecord => item !== null);\n }\n\n /**\n * Handle an OAuth callback URL\n *\n * Call this after the user has been redirected back from authorization.\n * This is required for web apps where `onAuthRequired` redirects instead of waiting.\n *\n * @param callbackUrl The full callback URL with query parameters\n */\n async handleCallback(callbackUrl: string | URL): Promise<void> {\n const { code, state, error, errorDescription } =\n parseOAuthCallback(callbackUrl);\n\n if (error) {\n this._authFlowResolve?.();\n this._authFlowResolve = null;\n throw new AuthorizationRequiredError(\n errorDescription ?? `OAuth error: ${error}`,\n );\n }\n\n const isValidState = await this.oauthProvider.validateState(state);\n if (!isValidState) {\n this._authFlowResolve?.();\n this._authFlowResolve = null;\n throw new OAuthError(\n \"OAuth state validation failed. The state parameter did not match. Retry the authorization flow.\",\n \"kontext_oauth_state_invalid\",\n );\n }\n\n if (!code) {\n this._authFlowResolve?.();\n this._authFlowResolve = null;\n throw new AuthorizationRequiredError(\n \"No authorization code in callback URL\",\n );\n }\n\n try {\n // Create transport if needed\n if (!this.transport) {\n this.transport = new StreamableHTTPClientTransport(\n new URL(this.mcpEndpointUrl),\n {\n authProvider: this.oauthProvider,\n },\n );\n }\n\n // Exchange code for tokens (via MCP SDK)\n await this.transport.finishAuth(code);\n\n // Get the tokens from the auth code flow.\n // The backend auto-exchange produces resource-scoped tokens directly —\n // no client-side token exchange needed.\n const tokens = await this.oauthProvider.tokens();\n if (!tokens?.access_token) {\n throw new AuthorizationRequiredError(\"Failed to obtain tokens\");\n }\n\n await this.oauthProvider.saveTokens(tokens);\n } finally {\n // Signal that auth flow completed\n this._authFlowResolve?.();\n this._authFlowResolve = null;\n }\n }\n\n /**\n * Disconnect from the server\n */\n async disconnect(): Promise<void> {\n try {\n if (this.transport) {\n try {\n await this.transport.terminateSession();\n } catch {\n // Ignore termination errors\n }\n await this.transport.close();\n }\n } finally {\n this.transport = null;\n this.client = null;\n this._isConnected = false;\n }\n }\n\n /**\n * Clear stored tokens and require re-authentication\n */\n async clearAuth(): Promise<void> {\n await this.oauthProvider.clearAll();\n await this.disconnect();\n }\n\n /**\n * Check if this URL is an OAuth callback\n *\n * Useful for web apps to detect if the current URL is a callback.\n *\n * @param url The URL to check\n */\n isCallback(url: string | URL): boolean {\n const urlObj = typeof url === \"string\" ? new URL(url) : url;\n const redirectUri = new URL(this.config.redirectUri);\n return (\n urlObj.pathname === redirectUri.pathname &&\n (urlObj.searchParams.has(\"code\") || urlObj.searchParams.has(\"error\"))\n );\n }\n\n /**\n * Ensure we're connected, handling auth if needed\n */\n private async ensureConnected(): Promise<void> {\n if (this._isConnected && this.client) {\n return;\n }\n\n // Prevent concurrent connection attempts\n if (this._pendingConnect) {\n await this._pendingConnect;\n return;\n }\n\n this._pendingConnect = this.doConnect();\n try {\n await this._pendingConnect;\n } finally {\n this._pendingConnect = null;\n }\n }\n\n /**\n * Internal connection logic\n */\n private async doConnect(authRetryCount = 0): Promise<void> {\n // Tokens from auth code flow are already resource-scoped —\n // no client-side exchange needed.\n\n // Create transport if needed (may already exist from auth flow)\n if (!this.transport) {\n this.transport = new StreamableHTTPClientTransport(\n new URL(this.mcpEndpointUrl),\n {\n authProvider: this.oauthProvider,\n },\n );\n }\n\n const capabilities: Record<string, Record<string, unknown>> = {\n tools: {},\n };\n if (this.config.onElicitationUrl) {\n capabilities.elicitation = { url: {} };\n }\n\n this.client = new Client(\n {\n name: this.config.clientName ?? \"kontext-sdk\",\n version: this.config.clientVersion ?? \"0.0.1\",\n },\n { capabilities },\n );\n\n // Register elicitation handlers when callback is provided\n if (this.config.onElicitationUrl) {\n const onElicitationUrl = this.config.onElicitationUrl;\n\n // Handle server-initiated elicitation requests (request-based)\n this.client.setRequestHandler(ElicitRequestSchema, async (request) => {\n const params = request.params;\n if (params.mode === \"url\" && \"url\" in params) {\n await onElicitationUrl({\n url: params.url,\n message: params.message ?? \"Action required\",\n elicitationId: params.elicitationId ?? \"\",\n integrationId: (params as Record<string, unknown>).integrationId as\n | string\n | undefined,\n integrationName: (params as Record<string, unknown>)\n .integrationName as string | undefined,\n });\n }\n return { action: \"accept\" as const };\n });\n\n // Handle elicitation completion notifications\n this.client.setNotificationHandler(\n ElicitationCompleteNotificationSchema,\n () => {\n // Completion notification received — no action needed from the client.\n // The server will retry the tool call automatically.\n },\n );\n }\n\n try {\n await this.client.connect(this.transport);\n this._isConnected = true;\n } catch (error) {\n // If UnauthorizedError, wait for pending auth flow to complete and retry\n if (error instanceof Error && isUnauthorizedError(error)) {\n if (this._pendingAuthFlow) {\n // Auth flow was triggered - wait for it to complete\n await this._pendingAuthFlow;\n this._pendingAuthFlow = null;\n\n // Clean up both - we need fresh instances for retry\n // The transport was already started and can't be reused\n this.transport = null;\n this.client = null;\n\n if (authRetryCount >= 1) {\n throw new AuthorizationRequiredError(\n \"Authorization completed, but the MCP server still rejected the token. Verify OAuth resource audience and token issuer configuration.\",\n { cause: error },\n );\n }\n\n // Retry connection after auth completed\n return this.doConnect(authRetryCount + 1);\n }\n\n // No pending auth flow - clean up and throw error\n this.transport = null;\n this.client = null;\n throw new AuthorizationRequiredError(\n \"Authorization required. Complete the OAuth flow and retry.\",\n );\n }\n\n // Other errors - clean up and wrap in KontextError\n this.transport = null;\n this.client = null;\n if (error instanceof KontextError) throw error;\n throw new KontextError(\n `Failed to connect to MCP server at ${this.mcpEndpointUrl}. ${error instanceof Error ? error.message : String(error)}`,\n \"kontext_mcp_connection_failed\",\n { cause: error },\n );\n }\n }\n}\n\n// Re-export types\nexport type { Tool, CallToolResult } from \"@modelcontextprotocol/sdk/types.js\";\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/storage/memory.ts","../../src/storage/types.ts","../../src/errors.ts","../../src/oauth/provider.ts","../../src/mcp/client.ts"],"names":["randomBytes","UrlElicitationRequiredError","StreamableHTTPClientTransport","Client","ElicitRequestSchema","ElicitationCompleteNotificationSchema"],"mappings":";;;;;;;;;;AAWO,IAAM,gBAAN,MAA8C;AAAA,EAC3C,KAAA,uBAAY,GAAA,EAAqB;AAAA,EAEzC,MAAM,QAAW,GAAA,EAAqC;AACpD,IAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,KAAA,CAAM,GAAA,CAAI,GAAG,CAAA;AAChC,IAAA,IAAI,UAAU,MAAA,EAAW;AACvB,MAAA,OAAO,MAAA;AAAA,IACT;AAEA,IAAA,OAAO,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,SAAA,CAAU,KAAK,CAAC,CAAA;AAAA,EACzC;AAAA,EAEA,MAAM,OAAA,CAAW,GAAA,EAAa,KAAA,EAAqC;AACjE,IAAA,IAAI,UAAU,MAAA,EAAW;AACvB,MAAA,IAAA,CAAK,KAAA,CAAM,OAAO,GAAG,CAAA;AAAA,IACvB,CAAA,MAAO;AAEL,MAAA,IAAA,CAAK,KAAA,CAAM,IAAI,GAAA,EAAK,IAAA,CAAK,MAAM,IAAA,CAAK,SAAA,CAAU,KAAK,CAAC,CAAC,CAAA;AAAA,IACvD;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,KAAA,GAAc;AACZ,IAAA,IAAA,CAAK,MAAM,KAAA,EAAM;AAAA,EACnB;AAAA;AAAA;AAAA;AAAA,EAKA,IAAI,IAAA,GAAe;AACjB,IAAA,OAAO,KAAK,KAAA,CAAM,IAAA;AAAA,EACpB;AAAA;AAAA;AAAA;AAAA,EAKA,IAAI,GAAA,EAAsB;AACxB,IAAA,OAAO,IAAA,CAAK,KAAA,CAAM,GAAA,CAAI,GAAG,CAAA;AAAA,EAC3B;AAAA;AAAA;AAAA;AAAA,EAKA,IAAA,GAAiB;AACf,IAAA,OAAO,KAAA,CAAM,IAAA,CAAK,IAAA,CAAK,KAAA,CAAM,MAAM,CAAA;AAAA,EACrC;AACF,CAA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AAA,EAAO;AAEd,MAAA,IAAI,KAAA,YAAiB,KAAA,IAAS,mBAAA,CAAoB,KAAK,CAAA,EAAG;AACxD,QAAA,IAAI,KAAK,gBAAA,EAAkB;AAEzB,UAAA,MAAM,IAAA,CAAK,gBAAA;AACX,UAAA,IAAA,CAAK,gBAAA,GAAmB,IAAA;AAIxB,UAAA,IAAA,CAAK,SAAA,GAAY,IAAA;AACjB,UAAA,IAAA,CAAK,MAAA,GAAS,IAAA;AAEd,UAAA,IAAI,kBAAkB,CAAA,EAAG;AACvB,YAAA,MAAM,IAAI,0BAAA;AAAA,cACR,sIAAA;AAAA,cACA,EAAE,OAAO,KAAA;AAAM,aACjB;AAAA,UACF;AAGA,UAAA,OAAO,IAAA,CAAK,SAAA,CAAU,cAAA,GAAiB,CAAC,CAAA;AAAA,QAC1C;AAGA,QAAA,IAAA,CAAK,SAAA,GAAY,IAAA;AACjB,QAAA,IAAA,CAAK,MAAA,GAAS,IAAA;AACd,QAAA,MAAM,IAAI,0BAAA;AAAA,UACR;AAAA,SACF;AAAA,MACF;AAGA,MAAA,IAAA,CAAK,SAAA,GAAY,IAAA;AACjB,MAAA,IAAA,CAAK,MAAA,GAAS,IAAA;AACd,MAAA,IAAI,KAAA,YAAiB,cAAc,MAAM,KAAA;AACzC,MAAA,MAAM,IAAI,YAAA;AAAA,QACR,CAAA,mCAAA,EAAsC,IAAA,CAAK,cAAc,CAAA,EAAA,EAAK,KAAA,YAAiB,QAAQ,KAAA,CAAM,OAAA,GAAU,MAAA,CAAO,KAAK,CAAC,CAAA,CAAA;AAAA,QACpH,+BAAA;AAAA,QACA,EAAE,OAAO,KAAA;AAAM,OACjB;AAAA,IACF;AAAA,EACF;AACF","file":"index.cjs","sourcesContent":["/**\n * In-memory storage implementation\n * Useful for tests, examples, and ephemeral sessions\n */\n\nimport type { KontextStorage } from \"./types.js\";\n\n/**\n * Simple in-memory storage implementation\n * Data is lost when the process exits\n */\nexport class MemoryStorage implements KontextStorage {\n private store = new Map<string, unknown>();\n\n async getJson<T>(key: string): Promise<T | undefined> {\n const value = this.store.get(key);\n if (value === undefined) {\n return undefined;\n }\n // Return a deep copy to prevent mutation\n return JSON.parse(JSON.stringify(value)) as T;\n }\n\n async setJson<T>(key: string, value: T | undefined): Promise<void> {\n if (value === undefined) {\n this.store.delete(key);\n } else {\n // Store a deep copy to prevent mutation\n this.store.set(key, JSON.parse(JSON.stringify(value)));\n }\n }\n\n /**\n * Clear all stored data\n */\n clear(): void {\n this.store.clear();\n }\n\n /**\n * Get the number of stored items\n */\n get size(): number {\n return this.store.size;\n }\n\n /**\n * Check if a key exists\n */\n has(key: string): boolean {\n return this.store.has(key);\n }\n\n /**\n * Get all keys (useful for debugging)\n */\n keys(): string[] {\n return Array.from(this.store.keys());\n }\n}\n","/**\n * Storage interface for persisting SDK state\n */\n\n/**\n * Generic storage interface for the Kontext SDK\n * Implementations can store data in memory, file system, or external services\n */\nexport interface KontextStorage {\n /**\n * Retrieve a JSON value by key\n * @param key Storage key\n * @returns The stored value or undefined if not found\n */\n getJson<T>(key: string): Promise<T | undefined>;\n\n /**\n * Store a JSON value by key\n * @param key Storage key\n * @param value The value to store, or undefined to delete\n */\n setJson<T>(key: string, value: T | undefined): Promise<void>;\n}\n\n/**\n * Storage key namespacing helper\n * Creates namespaced keys based on application client ID and optional session key\n */\nexport function createStorageKey(\n applicationClientId: string,\n sessionKey: string | undefined,\n ...parts: string[]\n): string {\n const namespace = sessionKey\n ? `kontext:${applicationClientId}:${sessionKey}`\n : `kontext:${applicationClientId}`;\n return [namespace, ...parts].join(\":\");\n}\n\n/**\n * Storage keys used by the SDK\n */\nexport const StorageKeys = {\n // Existing keys\n TOKENS: \"tokens\",\n CODE_VERIFIER: \"code_verifier\",\n STATE: \"state\",\n CLIENT_INFO: \"client_info\",\n\n // Pattern B (RFC 8693 Token Exchange) keys\n /** Identity tokens (no audience) */\n IDENTITY_TOKENS: \"identity_tokens\",\n /** Prefix for resource-scoped tokens */\n RESOURCE_TOKENS: \"resource_tokens\",\n} as const;\n\n/**\n * Create a storage key for a resource-scoped token\n *\n * @param resource The resource identifier (e.g., \"mcp-gateway\")\n * @returns Storage key for the resource token\n *\n * @example\n * ```typescript\n * const key = resourceTokenKey('mcp-gateway');\n * // Returns: 'resource_tokens:mcp-gateway'\n * ```\n */\nexport function resourceTokenKey(resource: string): string {\n return `${StorageKeys.RESOURCE_TOKENS}:${resource}`;\n}\n","/**\n * Typed error classes for the Kontext SDK.\n *\n * Every error has a `kontext_` prefixed code, an auto-generated docsUrl,\n * and a `kontextError` brand for type narrowing without instanceof.\n *\n * @packageDocumentation\n */\n\n// ============================================================================\n// Base\n// ============================================================================\n\n/**\n * Base error class for all Kontext SDK errors.\n *\n * @example\n * ```typescript\n * import { isKontextError } from '@kontext-dev/js-sdk';\n *\n * try {\n * await client.connect();\n * } catch (err) {\n * if (isKontextError(err)) {\n * console.log(err.code); // \"kontext_authorization_required\"\n * console.log(err.docsUrl); // \"https://docs.kontext.dev/errors/kontext_authorization_required\"\n * }\n * }\n * ```\n */\nexport class KontextError extends Error {\n /** Brand field for type narrowing without instanceof */\n readonly kontextError = true as const;\n\n /** Machine-readable error code, always prefixed with `kontext_` */\n readonly code: string;\n\n /** HTTP status code when applicable */\n readonly statusCode?: number;\n\n /** Auto-generated link to error documentation */\n readonly docsUrl: string;\n\n /** Server request ID for debugging / support escalation */\n readonly requestId?: string;\n\n /** Contextual metadata bag (integration IDs, param names, etc.) */\n readonly meta: Record<string, unknown>;\n\n constructor(\n message: string,\n code: string,\n options?: {\n statusCode?: number;\n requestId?: string;\n meta?: Record<string, unknown>;\n cause?: unknown;\n },\n ) {\n super(message, { cause: options?.cause });\n this.name = \"KontextError\";\n this.code = code;\n this.statusCode = options?.statusCode;\n this.requestId = options?.requestId;\n this.meta = options?.meta ?? {};\n this.docsUrl = `https://docs.kontext.dev/errors/${code}`;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n toJSON(): Record<string, unknown> {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n statusCode: this.statusCode,\n docsUrl: this.docsUrl,\n requestId: this.requestId,\n meta: Object.keys(this.meta).length > 0 ? this.meta : undefined,\n };\n }\n\n override toString(): string {\n const parts = [`[${this.code}] ${this.message}`];\n if (this.docsUrl) parts.push(`Docs: ${this.docsUrl}`);\n if (this.requestId) parts.push(`Request ID: ${this.requestId}`);\n return parts.join(\"\\n\");\n }\n}\n\n// ============================================================================\n// Type guard\n// ============================================================================\n\n/**\n * Check if an error is a KontextError without instanceof.\n * Works across package versions and bundler deduplication.\n */\nexport function isKontextError(err: unknown): err is KontextError {\n return (\n typeof err === \"object\" &&\n err !== null &&\n (err as Record<string, unknown>).kontextError === true\n );\n}\n\n// ============================================================================\n// Auth errors\n// ============================================================================\n\n/**\n * Thrown when authentication is required but no valid credentials are available.\n */\nexport class AuthorizationRequiredError extends KontextError {\n readonly authorizationUrl?: string;\n\n constructor(\n message = \"Authorization required. Complete the OAuth flow to continue.\",\n options?: {\n authorizationUrl?: string;\n requestId?: string;\n meta?: Record<string, unknown>;\n cause?: unknown;\n },\n ) {\n super(message, \"kontext_authorization_required\", {\n statusCode: 401,\n ...options,\n });\n this.name = \"AuthorizationRequiredError\";\n this.authorizationUrl = options?.authorizationUrl;\n }\n}\n\n// ============================================================================\n// OAuth errors\n// ============================================================================\n\n/**\n * Thrown when an OAuth flow fails — state validation, token exchange,\n * missing code verifier, or provider errors.\n */\nexport class OAuthError extends KontextError {\n readonly errorCode?: string;\n readonly errorDescription?: string;\n\n constructor(\n message: string,\n code: string,\n options?: {\n statusCode?: number;\n errorCode?: string;\n errorDescription?: string;\n requestId?: string;\n meta?: Record<string, unknown>;\n cause?: unknown;\n },\n ) {\n super(message, code, {\n statusCode: options?.statusCode ?? 400,\n ...options,\n });\n this.name = \"OAuthError\";\n this.errorCode = options?.errorCode;\n this.errorDescription = options?.errorDescription;\n }\n}\n\n// ============================================================================\n// Integration errors\n// ============================================================================\n\n/**\n * Thrown when an integration connection is required before a tool can be used.\n */\nexport class IntegrationConnectionRequiredError extends KontextError {\n readonly integrationId: string;\n readonly integrationName?: string;\n readonly connectUrl?: string;\n\n constructor(\n integrationId: string,\n options?: {\n integrationName?: string;\n connectUrl?: string;\n message?: string;\n requestId?: string;\n meta?: Record<string, unknown>;\n cause?: unknown;\n },\n ) {\n super(\n options?.message ??\n `Connection to integration \"${integrationId}\" is required. Visit the connect URL to authorize.`,\n \"kontext_integration_connection_required\",\n { statusCode: 403, ...options },\n );\n this.name = \"IntegrationConnectionRequiredError\";\n this.integrationId = integrationId;\n this.integrationName = options?.integrationName;\n this.connectUrl = options?.connectUrl;\n }\n}\n\n// ============================================================================\n// Config errors (NEW — replaces all plain Error config throws)\n// ============================================================================\n\n/**\n * Thrown when SDK configuration is invalid or missing.\n * These are deterministic errors caught at initialization time.\n */\nexport class ConfigError extends KontextError {\n constructor(\n message: string,\n code: string,\n options?: {\n meta?: Record<string, unknown>;\n cause?: unknown;\n },\n ) {\n super(message, code, options);\n this.name = \"ConfigError\";\n }\n}\n\n// ============================================================================\n// Network errors\n// ============================================================================\n\n/**\n * Thrown when there is a network or connection error.\n */\nexport class NetworkError extends KontextError {\n constructor(\n message = \"Network error. Check your internet connection and that the server is reachable.\",\n options?: {\n cause?: unknown;\n requestId?: string;\n meta?: Record<string, unknown>;\n },\n ) {\n super(message, \"kontext_network_error\", options);\n this.name = \"NetworkError\";\n }\n}\n\n// ============================================================================\n// HTTP response errors (differentiated by code)\n// ============================================================================\n\n/**\n * Thrown when the server returns an HTTP error.\n * Use `error.code` to distinguish between specific error types.\n */\nexport class HttpError extends KontextError {\n readonly retryAfter?: number;\n readonly validationErrors?: Array<{ field: string; message: string }>;\n\n constructor(\n message: string,\n code: string,\n options?: {\n statusCode?: number;\n retryAfter?: number;\n validationErrors?: Array<{ field: string; message: string }>;\n requestId?: string;\n meta?: Record<string, unknown>;\n cause?: unknown;\n },\n ) {\n super(message, code, {\n statusCode: options?.statusCode,\n ...options,\n });\n this.name = \"HttpError\";\n this.retryAfter = options?.retryAfter;\n this.validationErrors = options?.validationErrors;\n }\n}\n\n// ============================================================================\n// Network error detection (used by translateError)\n// ============================================================================\n\n/**\n * Safely access arbitrary properties on an error object.\n * Errors in JS frequently carry extra properties (code, statusCode, etc.)\n * that aren't part of the Error interface. This avoids `as unknown as` casts.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction errorProps(err: Error): Record<string, any> {\n return err;\n}\n\nconst NETWORK_ERROR_CODES = new Set([\n \"ECONNREFUSED\",\n \"ENOTFOUND\",\n \"ETIMEDOUT\",\n \"ECONNRESET\",\n \"ECONNABORTED\",\n \"EPIPE\",\n \"UND_ERR_CONNECT_TIMEOUT\",\n]);\n\n/**\n * Detect network errors structurally rather than by string matching.\n * Checks Node.js system error codes on the error and its cause.\n */\nexport function isNetworkError(err: Error): boolean {\n if (err.name === \"AbortError\") return true;\n\n const props = errorProps(err);\n const sysCode = props.code as string | undefined;\n if (typeof sysCode === \"string\" && NETWORK_ERROR_CODES.has(sysCode))\n return true;\n\n // fetch() throws TypeError — only classify as network error when cause\n // indicates a system-level failure\n if (err.name === \"TypeError\" && err.cause instanceof Error) {\n const causeCode = errorProps(err.cause).code;\n if (typeof causeCode === \"string\" && NETWORK_ERROR_CODES.has(causeCode))\n return true;\n }\n\n return false;\n}\n\n/**\n * Detect unauthorized errors structurally.\n * Checks status code and numeric code rather than string matching on name.\n */\nexport function isUnauthorizedError(err: Error): boolean {\n const props = errorProps(err);\n\n // Check HTTP status code (most reliable)\n if (props.statusCode === 401 || props.status === 401) return true;\n\n // Check MCP SDK UnauthorizedError by name (last resort, but needed for\n // MCP SDK errors which don't set statusCode)\n if (err.name === \"UnauthorizedError\") return true;\n if (err.message === \"Unauthorized\") return true;\n\n return false;\n}\n\n// ============================================================================\n// Elicitation types\n// ============================================================================\n\nexport interface ElicitationEntry {\n readonly url: string;\n readonly message: string;\n readonly elicitationId: string;\n readonly integrationId?: string;\n readonly integrationName?: string;\n}\n\n// ============================================================================\n// HTTP error parsing\n// ============================================================================\n\n/**\n * Parse an HTTP response into an appropriate error.\n */\nexport function parseHttpError(\n statusCode: number,\n body?: unknown,\n): KontextError {\n const message =\n typeof body === \"object\" && body !== null && \"message\" in body\n ? String((body as { message: unknown }).message)\n : `HTTP ${statusCode}`;\n\n const errorCode =\n typeof body === \"object\" && body !== null && \"code\" in body\n ? String((body as { code: unknown }).code)\n : undefined;\n\n switch (statusCode) {\n case 400:\n if (\n typeof body === \"object\" &&\n body !== null &&\n \"errors\" in body &&\n Array.isArray((body as { errors: unknown }).errors)\n ) {\n return new HttpError(message, \"kontext_validation_error\", {\n statusCode: 400,\n validationErrors: (\n body as { errors: Array<{ field: string; message: string }> }\n ).errors,\n });\n }\n return new KontextError(message, errorCode ?? \"kontext_bad_request\", {\n statusCode: 400,\n });\n\n case 401:\n return new AuthorizationRequiredError(message);\n\n case 403:\n if (errorCode === \"INTEGRATION_CONNECTION_REQUIRED\") {\n const details = body as {\n integrationId?: string;\n integrationName?: string;\n connectUrl?: string;\n };\n return new IntegrationConnectionRequiredError(\n details.integrationId ?? \"unknown\",\n {\n integrationName: details.integrationName,\n connectUrl: details.connectUrl,\n message,\n },\n );\n }\n return new HttpError(message, \"kontext_policy_denied\", {\n statusCode: 403,\n meta: { policy: (body as Record<string, unknown>)?.policy },\n });\n\n case 404:\n return new HttpError(message, \"kontext_not_found\", { statusCode: 404 });\n\n case 429: {\n const retryAfter =\n typeof body === \"object\" && body !== null && \"retryAfter\" in body\n ? Number((body as { retryAfter: unknown }).retryAfter)\n : undefined;\n return new HttpError(\n retryAfter\n ? `Rate limit exceeded. Retry after ${retryAfter} seconds.`\n : \"Rate limit exceeded. Wait and retry.\",\n \"kontext_rate_limited\",\n { statusCode: 429, retryAfter },\n );\n }\n\n default:\n if (statusCode >= 500) {\n return new HttpError(\n `Server error (HTTP ${statusCode}): ${message}`,\n \"kontext_server_error\",\n { statusCode },\n );\n }\n return new KontextError(message, errorCode ?? \"kontext_unknown_error\", {\n statusCode,\n });\n }\n}\n","/**\n * KontextOAuthProvider - Implements OAuthClientProvider from @modelcontextprotocol/sdk\n *\n * This provider handles the OAuth 2.0 Authorization Code + PKCE flow\n * for authenticating MCP clients with the Kontext Gateway.\n */\n\nimport type { OAuthClientProvider } from \"@modelcontextprotocol/sdk/client/auth.js\";\nimport type {\n OAuthClientMetadata,\n OAuthClientInformationMixed,\n OAuthTokens,\n} from \"@modelcontextprotocol/sdk/shared/auth.js\";\nimport { randomBytes } from \"node:crypto\";\nimport type { KontextStorage } from \"../storage/types.js\";\nimport {\n createStorageKey,\n StorageKeys,\n resourceTokenKey,\n} from \"../storage/types.js\";\nimport { OAuthError } from \"../errors.js\";\n\nexport interface KontextOAuthProviderConfig {\n /**\n * Application OAuth client ID from Kontext\n */\n clientId: string;\n\n /**\n * Redirect URI for OAuth callback\n * Must match one of the registered redirect URIs for the application\n */\n redirectUri: string;\n\n /**\n * Storage implementation for persisting tokens and PKCE state\n */\n storage: KontextStorage;\n\n /**\n * Optional session key for namespacing storage\n * Useful when multiple users/sessions share the same storage\n */\n sessionKey?: string;\n\n /**\n * Optional client name for OAuth metadata\n */\n clientName?: string;\n\n /**\n * Callback to redirect the user agent to the authorization URL\n * This is called when authorization is required\n *\n * @param url The authorization URL to redirect to\n */\n onRedirectToAuthorization: (url: URL) => void | Promise<void>;\n}\n\n/**\n * OAuth provider implementation for Kontext MCP clients\n *\n * Implements the OAuthClientProvider interface from @modelcontextprotocol/sdk\n * to handle Authorization Code + PKCE authentication flow.\n *\n * @example\n * ```typescript\n * const storage = new MemoryStorage();\n * const provider = new KontextOAuthProvider({\n * clientId: 'your-client-id',\n * redirectUri: 'http://localhost:3000/callback',\n * storage,\n * onRedirectToAuthorization: (url) => {\n * // Open browser or redirect\n * window.location.href = url.toString();\n * },\n * });\n * ```\n */\nexport class KontextOAuthProvider implements OAuthClientProvider {\n private readonly config: KontextOAuthProviderConfig;\n private readonly storagePrefix: string;\n private pendingState: string | null = null;\n private readonly expiryBufferMs = 60 * 1000;\n\n constructor(config: KontextOAuthProviderConfig) {\n this.config = config;\n this.storagePrefix = createStorageKey(config.clientId, config.sessionKey);\n }\n\n /**\n * The redirect URL for OAuth callbacks\n */\n get redirectUrl(): string | URL {\n return this.config.redirectUri;\n }\n\n /**\n * OAuth client metadata\n */\n get clientMetadata(): OAuthClientMetadata {\n return {\n redirect_uris: [this.config.redirectUri],\n client_name: this.config.clientName,\n grant_types: [\"authorization_code\", \"refresh_token\"],\n response_types: [\"code\"],\n token_endpoint_auth_method: \"none\", // Public client\n };\n }\n\n /**\n * Generate a random state parameter for OAuth CSRF protection\n */\n state(): string {\n // Generate a cryptographically secure random string\n const array = new Uint8Array(32);\n if (globalThis.crypto?.getRandomValues) {\n globalThis.crypto.getRandomValues(array);\n } else {\n array.set(randomBytes(32));\n }\n const state = Array.from(array, (byte) =>\n byte.toString(16).padStart(2, \"0\"),\n ).join(\"\");\n this.pendingState = state;\n void this.config.storage.setJson(\n this.getStorageKey(StorageKeys.STATE),\n state,\n );\n return state;\n }\n\n /**\n * Returns the client information (client_id)\n * Since we're a public client with pre-registered credentials,\n * we don't use dynamic client registration.\n */\n async clientInformation(): Promise<OAuthClientInformationMixed | undefined> {\n return {\n client_id: this.config.clientId,\n };\n }\n\n /**\n * Load stored OAuth tokens\n */\n async tokens(): Promise<OAuthTokens | undefined> {\n const key = this.getStorageKey(StorageKeys.TOKENS);\n return this.config.storage.getJson<OAuthTokens>(key);\n }\n\n /**\n * Save OAuth tokens after successful authorization\n */\n async saveTokens(tokens: OAuthTokens): Promise<void> {\n const key = this.getStorageKey(StorageKeys.TOKENS);\n await this.config.storage.setJson(key, this.withIssuedAt(tokens));\n }\n\n /**\n * Redirect the user agent to the authorization URL\n */\n async redirectToAuthorization(authorizationUrl: URL): Promise<void> {\n await this.config.onRedirectToAuthorization(authorizationUrl);\n }\n\n /**\n * Save the PKCE code verifier before redirecting to authorization\n */\n async saveCodeVerifier(codeVerifier: string): Promise<void> {\n const key = this.getStorageKey(StorageKeys.CODE_VERIFIER);\n await this.config.storage.setJson(key, codeVerifier);\n }\n\n /**\n * Load the PKCE code verifier for token exchange\n */\n async codeVerifier(): Promise<string> {\n const key = this.getStorageKey(StorageKeys.CODE_VERIFIER);\n const verifier = await this.config.storage.getJson<string>(key);\n if (!verifier) {\n throw new OAuthError(\n \"No PKCE code verifier found in storage. The OAuth flow may have expired or storage was cleared. Restart the auth flow.\",\n \"kontext_oauth_code_verifier_missing\",\n );\n }\n return verifier;\n }\n\n /**\n * Invalidate stored credentials\n */\n async invalidateCredentials(\n scope: \"all\" | \"client\" | \"tokens\" | \"verifier\",\n ): Promise<void> {\n if (scope === \"all\" || scope === \"tokens\") {\n const tokensKey = this.getStorageKey(StorageKeys.TOKENS);\n await this.config.storage.setJson(tokensKey, undefined);\n const identityKey = this.getStorageKey(StorageKeys.IDENTITY_TOKENS);\n await this.config.storage.setJson(identityKey, undefined);\n }\n if (scope === \"all\" || scope === \"verifier\") {\n const verifierKey = this.getStorageKey(StorageKeys.CODE_VERIFIER);\n await this.config.storage.setJson(verifierKey, undefined);\n }\n if (scope === \"all\") {\n this.pendingState = null;\n const stateKey = this.getStorageKey(StorageKeys.STATE);\n await this.config.storage.setJson(stateKey, undefined);\n }\n // 'client' scope is a no-op since we use pre-registered client info\n }\n\n /**\n * Clear all stored state (tokens, verifier, etc.)\n * Call this to force re-authentication\n */\n async clearAll(): Promise<void> {\n await this.invalidateCredentials(\"all\");\n }\n\n /**\n * Check if we have valid (non-expired) tokens\n */\n async hasValidTokens(): Promise<boolean> {\n const storedTokens = await this.tokens();\n return this.isTokenValid(storedTokens);\n }\n\n // ==========================================================================\n // Pattern B: Identity and Resource Token Management (RFC 8693)\n // ==========================================================================\n\n /**\n * Save identity tokens (no audience)\n * These are the tokens obtained from the initial OAuth flow before token exchange.\n */\n async saveIdentityTokens(tokens: OAuthTokens): Promise<void> {\n const key = this.getStorageKey(StorageKeys.IDENTITY_TOKENS);\n await this.config.storage.setJson(key, this.withIssuedAt(tokens));\n }\n\n /**\n * Load identity tokens\n * Returns the identity tokens obtained from the initial OAuth flow.\n */\n async identityTokens(): Promise<OAuthTokens | undefined> {\n const key = this.getStorageKey(StorageKeys.IDENTITY_TOKENS);\n return this.config.storage.getJson<OAuthTokens>(key);\n }\n\n /**\n * Save resource-scoped tokens for a specific resource\n *\n * @param resource The resource identifier (e.g., \"mcp-gateway\")\n * @param tokens The resource-scoped tokens\n */\n async saveResourceTokens(\n resource: string,\n tokens: OAuthTokens,\n ): Promise<void> {\n const key = this.getStorageKey(resourceTokenKey(resource));\n await this.config.storage.setJson(key, this.withIssuedAt(tokens));\n }\n\n /**\n * Load resource-scoped tokens for a specific resource\n *\n * @param resource The resource identifier (e.g., \"mcp-gateway\")\n * @returns The resource-scoped tokens, or undefined if not found\n */\n async resourceTokens(resource: string): Promise<OAuthTokens | undefined> {\n const key = this.getStorageKey(resourceTokenKey(resource));\n return this.config.storage.getJson<OAuthTokens>(key);\n }\n\n /**\n * Clear resource tokens for a specific resource\n *\n * @param resource The resource identifier (e.g., \"mcp-gateway\")\n */\n async clearResourceTokens(resource: string): Promise<void> {\n const key = this.getStorageKey(resourceTokenKey(resource));\n await this.config.storage.setJson(key, undefined);\n }\n\n /**\n * Check if we have valid identity tokens\n */\n async hasValidIdentityTokens(): Promise<boolean> {\n const tokens = await this.identityTokens();\n return this.isTokenValid(tokens);\n }\n\n /**\n * Check if we have valid resource tokens for a specific resource\n *\n * @param resource The resource identifier\n */\n async hasValidResourceTokens(resource: string): Promise<boolean> {\n const tokens = await this.resourceTokens(resource);\n return this.isTokenValid(tokens);\n }\n\n async validateState(state?: string): Promise<boolean> {\n if (!state) {\n return false;\n }\n\n const key = this.getStorageKey(StorageKeys.STATE);\n const storedState =\n this.pendingState ?? (await this.config.storage.getJson<string>(key));\n const isValid = storedState === state;\n\n if (isValid) {\n this.pendingState = null;\n await this.config.storage.setJson(key, undefined);\n }\n\n return isValid;\n }\n\n private withIssuedAt(\n tokens: OAuthTokens,\n ): OAuthTokens & { issued_at?: number } {\n if (!tokens.expires_in) {\n return tokens;\n }\n return { ...tokens, issued_at: Date.now() };\n }\n\n private isTokenValid(tokens?: OAuthTokens): boolean {\n if (!tokens?.access_token) {\n return false;\n }\n\n if (!tokens.expires_in) {\n return true;\n }\n\n const issuedAt = (tokens as OAuthTokens & { issued_at?: number }).issued_at;\n if (!issuedAt) {\n return true;\n }\n\n const expiresAt = issuedAt + tokens.expires_in * 1000;\n return Date.now() < expiresAt - this.expiryBufferMs;\n }\n\n private getStorageKey(key: string): string {\n return `${this.storagePrefix}:${key}`;\n }\n}\n\n/**\n * Parse an OAuth callback URL and extract the authorization code and state\n *\n * @param callbackUrl The full callback URL with query parameters\n * @returns The authorization code and state, or error details\n */\nexport function parseOAuthCallback(callbackUrl: string | URL): {\n code?: string;\n state?: string;\n error?: string;\n errorDescription?: string;\n} {\n const url =\n typeof callbackUrl === \"string\" ? new URL(callbackUrl) : callbackUrl;\n const params = url.searchParams;\n\n const error = params.get(\"error\");\n if (error) {\n return {\n error,\n errorDescription: params.get(\"error_description\") ?? undefined,\n };\n }\n\n return {\n code: params.get(\"code\") ?? undefined,\n state: params.get(\"state\") ?? undefined,\n };\n}\n","/**\n * KontextMcp - Runtime client for MCP connections via Kontext\n *\n * This is the main entrypoint for MCP clients using Kontext.\n * It wraps the MCP SDK's Client and StreamableHTTPClientTransport\n * with Kontext-specific OAuth handling.\n *\n * Authentication is handled transparently:\n * 1. First API call triggers OAuth if needed\n * 2. Connection is established lazily\n *\n * All MCP servers (gateway and custom) are treated identically —\n * the auth code flow produces resource-scoped tokens directly.\n *\n * @example\n * ```typescript\n * import { KontextMcp } from '@kontext-dev/js-sdk';\n *\n * const kontext = new KontextMcp({\n * clientId: 'your-client-id',\n * redirectUri: 'http://localhost:3000/callback',\n * onAuthRequired: async (url) => {\n * // CLI: open browser, wait for callback, return URL\n * // Web: redirect (return nothing, handle callback separately)\n * open(url.toString());\n * return await waitForCallback();\n * },\n * });\n *\n * // Just use it - auth happens automatically\n * const tools = await kontext.listTools();\n * const result = await kontext.callTool('tool_name', { arg: 'value' });\n * ```\n */\n\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport {\n type Tool,\n type CallToolResult,\n type Implementation,\n UrlElicitationRequiredError,\n ElicitRequestSchema,\n ElicitationCompleteNotificationSchema,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type { KontextStorage } from \"../storage/types.js\";\nimport { MemoryStorage } from \"../storage/memory.js\";\nimport { KontextOAuthProvider, parseOAuthCallback } from \"../oauth/provider.js\";\nimport {\n AuthorizationRequiredError,\n OAuthError,\n KontextError,\n isUnauthorizedError,\n} from \"../errors.js\";\nimport type { ElicitationEntry } from \"../errors.js\";\n\n/**\n * Default Kontext API server URL\n */\nconst DEFAULT_SERVER = \"https://api.kontext.dev\";\n\nexport function normalizeKontextServerUrl(server: string): string {\n let url = server.replace(/\\/$/, \"\");\n\n // Be forgiving if callers pass a versioned API URL or MCP URL instead of the root origin.\n // Data-plane routes (/mcp, /oauth2, /.well-known) are intentionally outside /api/v1.\n url = url.replace(/\\/api\\/v1\\/?$/, \"\").replace(/\\/mcp\\/?$/, \"\");\n url = url.replace(/\\/$/, \"\");\n\n return url;\n}\n\nexport interface KontextMcpConfig {\n /**\n * Application OAuth client ID\n */\n clientId: string;\n\n /**\n * Full URL of the MCP server endpoint.\n * When provided, the client connects directly to this URL.\n *\n * @example \"https://my-server.com/mcp\"\n */\n url?: string;\n\n /**\n * Base URL for the Kontext server.\n * Defaults to \"https://api.kontext.dev\".\n * Only override for local development or self-hosted instances.\n */\n server?: string;\n\n /**\n * Redirect URI for OAuth callback\n * Must match one of the registered redirect URIs for the application\n */\n redirectUri: string;\n\n /**\n * Storage implementation for persisting tokens\n * Defaults to MemoryStorage if not provided\n */\n storage?: KontextStorage;\n\n /**\n * Optional session key for namespacing storage\n * Useful when multiple users/sessions share the same storage\n * Defaults to \"default\"\n */\n sessionKey?: string;\n\n /**\n * Client name for identification in MCP protocol\n */\n clientName?: string;\n\n /**\n * Client version for identification in MCP protocol\n */\n clientVersion?: string;\n\n /**\n * Callback invoked when OAuth authorization is required.\n *\n * For CLI/Desktop apps:\n * Open the browser, wait for the callback, and return the callback URL.\n * The SDK will extract the code and complete the flow.\n *\n * For Web apps:\n * Redirect to the URL (return nothing). After redirect back,\n * call `handleCallback(url)` on a fresh instance.\n *\n * @param url The authorization URL to open/redirect to\n * @returns The callback URL (CLI/Desktop) or void/Promise<void> (Web)\n */\n onAuthRequired: (\n url: URL,\n ) => string | URL | void | Promise<string | URL | void>;\n\n /**\n * Callback invoked when the server requests URL elicitation (MCP spec -32042).\n * This is the protocol-native way for servers to ask the user to visit a URL\n * (e.g., to connect an OAuth integration).\n *\n * When provided, the client declares `elicitation: { url: {} }` capability.\n */\n onElicitationUrl?: (entry: ElicitationEntry) => void | Promise<void>;\n}\n\nexport type RuntimeIntegrationCategory =\n | \"gateway_remote_mcp\"\n | \"internal_mcp_credentials\";\n\nexport type RuntimeIntegrationConnectType =\n | \"oauth\"\n | \"user_token\"\n | \"credentials\"\n | \"none\";\n\nexport interface RuntimeIntegrationRecord {\n id: string;\n name: string;\n url: string;\n category: RuntimeIntegrationCategory;\n connectType: RuntimeIntegrationConnectType;\n authMode?: \"oauth\" | \"user_token\" | \"server_token\" | \"none\";\n tokenLabel?: string;\n tokenHelpUrl?: string;\n tokenPlaceholder?: string;\n credentialSchema?: unknown;\n requiresOauth?: boolean;\n connection?: {\n connected: boolean;\n status: \"connected\" | \"disconnected\";\n expiresAt?: string;\n displayName?: string;\n };\n}\n\n/**\n * Kontext MCP runtime client\n *\n * Provides a simplified interface for connecting to any MCP server\n * and interacting with tools. Authentication is handled automatically.\n */\nexport class KontextMcp {\n private readonly config: KontextMcpConfig;\n private readonly storage: KontextStorage;\n private readonly oauthProvider: KontextOAuthProvider;\n private readonly clientSessionId =\n typeof globalThis.crypto?.randomUUID === \"function\"\n ? globalThis.crypto.randomUUID()\n : `kontext-sdk-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;\n private transport: StreamableHTTPClientTransport | null = null;\n private client: Client | null = null;\n private _isConnected = false;\n private _pendingConnect: Promise<void> | null = null;\n private _pendingAuthFlow: Promise<void> | null = null;\n private _authFlowResolve: (() => void) | null = null;\n\n constructor(config: KontextMcpConfig) {\n this.config = config;\n this.storage = config.storage ?? new MemoryStorage();\n\n this.oauthProvider = new KontextOAuthProvider({\n clientId: config.clientId,\n redirectUri: config.redirectUri,\n storage: this.storage,\n sessionKey: config.sessionKey ?? \"default\",\n clientName: config.clientName,\n onRedirectToAuthorization: async (url) => {\n // Create a promise that resolves when auth completes\n this._pendingAuthFlow = new Promise<void>((resolve) => {\n this._authFlowResolve = resolve;\n });\n\n // Delegate to user's callback\n const result = await config.onAuthRequired(url);\n if (result) {\n // User returned a callback URL - complete the flow\n await this.handleCallback(result);\n }\n // If no result, user redirected (web app) - they'll call handleCallback separately\n },\n });\n }\n\n /**\n * Check if we're currently connected\n */\n get isConnected(): boolean {\n return this._isConnected;\n }\n\n /**\n * Get the underlying MCP client for advanced usage\n */\n get mcpClient(): Client | null {\n return this.client;\n }\n\n /**\n * Get the session ID from the transport\n */\n get sessionId(): string | undefined {\n return this.transport?.sessionId;\n }\n\n /**\n * Get the server base URL\n */\n private get serverUrl(): string {\n return normalizeKontextServerUrl(this.config.server ?? DEFAULT_SERVER);\n }\n\n /**\n * Get the MCP endpoint URL.\n * When `url` is provided, use it directly. Otherwise derive from server.\n */\n private get mcpEndpointUrl(): string {\n return this.config.url ?? `${this.serverUrl}/mcp`;\n }\n\n /**\n * List available tools from the server\n *\n * This will automatically handle authentication if needed.\n */\n async listTools(): Promise<Tool[]> {\n await this.ensureConnected();\n const response = await this.client!.listTools();\n return response.tools;\n }\n\n /**\n * Call a tool\n *\n * This will automatically handle authentication if needed.\n *\n * @param name The tool name\n * @param args The tool arguments\n */\n async callTool(\n name: string,\n args?: Record<string, unknown>,\n ): Promise<CallToolResult> {\n await this.ensureConnected();\n try {\n const result = await this.client!.callTool({\n name,\n arguments: args,\n });\n return result as CallToolResult;\n } catch (error) {\n // Handle error-based URL elicitation (MCP -32042)\n if (\n error instanceof UrlElicitationRequiredError &&\n this.config.onElicitationUrl\n ) {\n for (const elicitation of error.elicitations) {\n await this.config.onElicitationUrl({\n url: elicitation.url,\n message: elicitation.message ?? \"Action required\",\n elicitationId: elicitation.elicitationId ?? \"\",\n integrationId: (elicitation as Record<string, unknown>)\n .integrationId as string | undefined,\n integrationName: (elicitation as Record<string, unknown>)\n .integrationName as string | undefined,\n });\n }\n }\n throw error;\n }\n }\n\n /**\n * Create a connect session for the hosted connect UI.\n *\n * Returns a URL that can be opened in a browser to let the user\n * connect integrations proactively (before hitting -32042 errors).\n */\n async createConnectSession(): Promise<{\n connectUrl: string;\n sessionId: string;\n expiresAt: string;\n }> {\n const tokens = await this.oauthProvider.tokens();\n if (!tokens?.access_token) {\n throw new AuthorizationRequiredError(\n \"Authorization required. Complete the OAuth flow first.\",\n );\n }\n\n const response = await fetch(`${this.serverUrl}/mcp/connect-session`, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${tokens.access_token}`,\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (response.status === 401) {\n throw new AuthorizationRequiredError(\n \"Access token expired or invalid. Re-authenticate and retry.\",\n );\n }\n\n if (!response.ok) {\n throw new KontextError(\n `Failed to create connect session: HTTP ${response.status}`,\n \"kontext_connect_session_failed\",\n { statusCode: response.status },\n );\n }\n\n return (await response.json()) as {\n connectUrl: string;\n sessionId: string;\n expiresAt: string;\n };\n }\n\n /**\n * List integrations attached to the current application/runtime identity.\n *\n * This is used by higher-level orchestrators to discover mixed integration\n * topologies (gateway + internal credential integrations).\n */\n async listRuntimeIntegrations(): Promise<RuntimeIntegrationRecord[]> {\n const tokens = await this.oauthProvider.tokens();\n if (!tokens?.access_token) {\n throw new AuthorizationRequiredError(\n \"Authorization required. Complete the OAuth flow first.\",\n );\n }\n\n const response = await fetch(`${this.serverUrl}/mcp/integrations`, {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${tokens.access_token}`,\n },\n });\n\n if (response.status === 401) {\n throw new AuthorizationRequiredError(\n \"Access token expired or invalid. Re-authenticate and retry.\",\n );\n }\n\n if (!response.ok) {\n throw new KontextError(\n `Failed to list runtime integrations: HTTP ${response.status}`,\n \"kontext_runtime_integrations_failed\",\n { statusCode: response.status },\n );\n }\n\n const payload = (await response.json()) as {\n items?: Array<Record<string, unknown>>;\n };\n const items = Array.isArray(payload?.items) ? payload.items : [];\n\n return items\n .map((item): RuntimeIntegrationRecord | null => {\n const id = typeof item.id === \"string\" ? item.id : \"\";\n const name = typeof item.name === \"string\" ? item.name : id;\n const url = typeof item.url === \"string\" ? item.url : \"\";\n if (!id || !url) return null;\n\n const category =\n item.category === \"internal_mcp_credentials\"\n ? \"internal_mcp_credentials\"\n : \"gateway_remote_mcp\";\n const rawConnectType = item.connectType;\n if (typeof rawConnectType !== \"string\") {\n throw new KontextError(\n \"Runtime integration connectType is required in API response.\",\n \"kontext_runtime_integrations_invalid_response\",\n { meta: { integrationId: id, connectType: rawConnectType } },\n );\n }\n\n const connectType =\n rawConnectType === \"credentials\" ||\n rawConnectType === \"oauth\" ||\n rawConnectType === \"user_token\" ||\n rawConnectType === \"none\"\n ? rawConnectType\n : null;\n\n if (!connectType) {\n throw new KontextError(\n `Unknown runtime integration connectType \"${rawConnectType}\".`,\n \"kontext_runtime_integrations_invalid_response\",\n { meta: { integrationId: id, connectType: rawConnectType } },\n );\n }\n\n const rawConnection =\n item.connection && typeof item.connection === \"object\"\n ? (item.connection as Record<string, unknown>)\n : undefined;\n const connected =\n rawConnection && typeof rawConnection.connected === \"boolean\"\n ? rawConnection.connected\n : false;\n const status =\n rawConnection?.status === \"connected\" ? \"connected\" : \"disconnected\";\n\n return {\n id,\n name,\n url,\n category,\n connectType,\n authMode:\n item.authMode === \"oauth\" ||\n item.authMode === \"user_token\" ||\n item.authMode === \"server_token\" ||\n item.authMode === \"none\"\n ? item.authMode\n : undefined,\n tokenLabel:\n typeof item.tokenLabel === \"string\" ? item.tokenLabel : undefined,\n tokenHelpUrl:\n typeof item.tokenHelpUrl === \"string\"\n ? item.tokenHelpUrl\n : undefined,\n tokenPlaceholder:\n typeof item.tokenPlaceholder === \"string\"\n ? item.tokenPlaceholder\n : undefined,\n credentialSchema: item.credentialSchema,\n requiresOauth:\n typeof item.requiresOauth === \"boolean\"\n ? item.requiresOauth\n : undefined,\n connection: rawConnection\n ? {\n connected,\n status,\n expiresAt:\n typeof rawConnection.expiresAt === \"string\"\n ? rawConnection.expiresAt\n : undefined,\n displayName:\n typeof rawConnection.displayName === \"string\"\n ? rawConnection.displayName\n : undefined,\n }\n : undefined,\n };\n })\n .filter((item): item is RuntimeIntegrationRecord => item !== null);\n }\n\n /**\n * Handle an OAuth callback URL\n *\n * Call this after the user has been redirected back from authorization.\n * This is required for web apps where `onAuthRequired` redirects instead of waiting.\n *\n * @param callbackUrl The full callback URL with query parameters\n */\n async handleCallback(callbackUrl: string | URL): Promise<void> {\n const { code, state, error, errorDescription } =\n parseOAuthCallback(callbackUrl);\n\n if (error) {\n this._authFlowResolve?.();\n this._authFlowResolve = null;\n throw new AuthorizationRequiredError(\n errorDescription ?? `OAuth error: ${error}`,\n );\n }\n\n const isValidState = await this.oauthProvider.validateState(state);\n if (!isValidState) {\n this._authFlowResolve?.();\n this._authFlowResolve = null;\n throw new OAuthError(\n \"OAuth state validation failed. The state parameter did not match. Retry the authorization flow.\",\n \"kontext_oauth_state_invalid\",\n );\n }\n\n if (!code) {\n this._authFlowResolve?.();\n this._authFlowResolve = null;\n throw new AuthorizationRequiredError(\n \"No authorization code in callback URL\",\n );\n }\n\n try {\n // Create transport if needed\n if (!this.transport) {\n this.transport = new StreamableHTTPClientTransport(\n new URL(this.mcpEndpointUrl),\n {\n authProvider: this.oauthProvider,\n },\n );\n }\n\n // Exchange code for tokens (via MCP SDK)\n await this.transport.finishAuth(code);\n\n // Get the tokens from the auth code flow.\n // The backend auto-exchange produces resource-scoped tokens directly —\n // no client-side token exchange needed.\n const tokens = await this.oauthProvider.tokens();\n if (!tokens?.access_token) {\n throw new AuthorizationRequiredError(\"Failed to obtain tokens\");\n }\n\n await this.oauthProvider.saveTokens(tokens);\n } finally {\n // Signal that auth flow completed\n this._authFlowResolve?.();\n this._authFlowResolve = null;\n }\n }\n\n /**\n * Disconnect from the server\n */\n async disconnect(): Promise<void> {\n try {\n if (this.transport) {\n try {\n await this.transport.terminateSession();\n } catch {\n // Ignore termination errors\n }\n await this.transport.close();\n }\n } finally {\n this.transport = null;\n this.client = null;\n this._isConnected = false;\n }\n }\n\n /**\n * Clear stored tokens and require re-authentication\n */\n async clearAuth(): Promise<void> {\n await this.oauthProvider.clearAll();\n await this.disconnect();\n }\n\n /**\n * Check if this URL is an OAuth callback\n *\n * Useful for web apps to detect if the current URL is a callback.\n *\n * @param url The URL to check\n */\n isCallback(url: string | URL): boolean {\n const urlObj = typeof url === \"string\" ? new URL(url) : url;\n const redirectUri = new URL(this.config.redirectUri);\n return (\n urlObj.pathname === redirectUri.pathname &&\n (urlObj.searchParams.has(\"code\") || urlObj.searchParams.has(\"error\"))\n );\n }\n\n /**\n * Ensure we're connected, handling auth if needed\n */\n private async ensureConnected(): Promise<void> {\n if (this._isConnected && this.client) {\n return;\n }\n\n // Prevent concurrent connection attempts\n if (this._pendingConnect) {\n await this._pendingConnect;\n return;\n }\n\n this._pendingConnect = this.doConnect();\n try {\n await this._pendingConnect;\n } finally {\n this._pendingConnect = null;\n }\n }\n\n /**\n * Internal connection logic\n */\n private async doConnect(authRetryCount = 0): Promise<void> {\n // Tokens from auth code flow are already resource-scoped —\n // no client-side exchange needed.\n\n // Create transport if needed (may already exist from auth flow)\n if (!this.transport) {\n this.transport = new StreamableHTTPClientTransport(\n new URL(this.mcpEndpointUrl),\n {\n authProvider: this.oauthProvider,\n },\n );\n }\n\n const capabilities: Record<string, Record<string, unknown>> = {\n tools: {},\n };\n if (this.config.onElicitationUrl) {\n capabilities.elicitation = { url: {} };\n }\n\n const clientInfo = {\n name: this.config.clientName ?? \"kontext-sdk\",\n version: this.config.clientVersion ?? \"0.0.1\",\n sessionId: this.clientSessionId,\n };\n\n this.client = new Client(clientInfo as unknown as Implementation, {\n capabilities,\n });\n\n // Register elicitation handlers when callback is provided\n if (this.config.onElicitationUrl) {\n const onElicitationUrl = this.config.onElicitationUrl;\n\n // Handle server-initiated elicitation requests (request-based)\n this.client.setRequestHandler(ElicitRequestSchema, async (request) => {\n const params = request.params;\n if (params.mode === \"url\" && \"url\" in params) {\n await onElicitationUrl({\n url: params.url,\n message: params.message ?? \"Action required\",\n elicitationId: params.elicitationId ?? \"\",\n integrationId: (params as Record<string, unknown>).integrationId as\n | string\n | undefined,\n integrationName: (params as Record<string, unknown>)\n .integrationName as string | undefined,\n });\n }\n return { action: \"accept\" as const };\n });\n\n // Handle elicitation completion notifications\n this.client.setNotificationHandler(\n ElicitationCompleteNotificationSchema,\n () => {\n // Completion notification received — no action needed from the client.\n // The server will retry the tool call automatically.\n },\n );\n }\n\n try {\n await this.client.connect(this.transport);\n this._isConnected = true;\n } catch (error) {\n // If UnauthorizedError, wait for pending auth flow to complete and retry\n if (error instanceof Error && isUnauthorizedError(error)) {\n if (this._pendingAuthFlow) {\n // Auth flow was triggered - wait for it to complete\n await this._pendingAuthFlow;\n this._pendingAuthFlow = null;\n\n // Clean up both - we need fresh instances for retry\n // The transport was already started and can't be reused\n this.transport = null;\n this.client = null;\n\n if (authRetryCount >= 1) {\n throw new AuthorizationRequiredError(\n \"Authorization completed, but the MCP server still rejected the token. Verify OAuth resource audience and token issuer configuration.\",\n { cause: error },\n );\n }\n\n // Retry connection after auth completed\n return this.doConnect(authRetryCount + 1);\n }\n\n // No pending auth flow - clean up and throw error\n this.transport = null;\n this.client = null;\n throw new AuthorizationRequiredError(\n \"Authorization required. Complete the OAuth flow and retry.\",\n );\n }\n\n // Other errors - clean up and wrap in KontextError\n this.transport = null;\n this.client = null;\n if (error instanceof KontextError) throw error;\n throw new KontextError(\n `Failed to connect to MCP server at ${this.mcpEndpointUrl}. ${error instanceof Error ? error.message : String(error)}`,\n \"kontext_mcp_connection_failed\",\n { cause: error },\n );\n }\n }\n}\n\n// Re-export types\nexport type { Tool, CallToolResult } from \"@modelcontextprotocol/sdk/types.js\";\n"]}
|
package/dist/mcp/index.d.cts
CHANGED
|
@@ -105,7 +105,7 @@ interface KontextMcpConfig {
|
|
|
105
105
|
onElicitationUrl?: (entry: ElicitationEntry) => void | Promise<void>;
|
|
106
106
|
}
|
|
107
107
|
type RuntimeIntegrationCategory = "gateway_remote_mcp" | "internal_mcp_credentials";
|
|
108
|
-
type RuntimeIntegrationConnectType = "oauth" | "credentials" | "none";
|
|
108
|
+
type RuntimeIntegrationConnectType = "oauth" | "user_token" | "credentials" | "none";
|
|
109
109
|
interface RuntimeIntegrationRecord {
|
|
110
110
|
id: string;
|
|
111
111
|
name: string;
|
|
@@ -113,6 +113,9 @@ interface RuntimeIntegrationRecord {
|
|
|
113
113
|
category: RuntimeIntegrationCategory;
|
|
114
114
|
connectType: RuntimeIntegrationConnectType;
|
|
115
115
|
authMode?: "oauth" | "user_token" | "server_token" | "none";
|
|
116
|
+
tokenLabel?: string;
|
|
117
|
+
tokenHelpUrl?: string;
|
|
118
|
+
tokenPlaceholder?: string;
|
|
116
119
|
credentialSchema?: unknown;
|
|
117
120
|
requiresOauth?: boolean;
|
|
118
121
|
connection?: {
|
|
@@ -132,6 +135,7 @@ declare class KontextMcp {
|
|
|
132
135
|
private readonly config;
|
|
133
136
|
private readonly storage;
|
|
134
137
|
private readonly oauthProvider;
|
|
138
|
+
private readonly clientSessionId;
|
|
135
139
|
private transport;
|
|
136
140
|
private client;
|
|
137
141
|
private _isConnected;
|
package/dist/mcp/index.d.ts
CHANGED
|
@@ -105,7 +105,7 @@ interface KontextMcpConfig {
|
|
|
105
105
|
onElicitationUrl?: (entry: ElicitationEntry) => void | Promise<void>;
|
|
106
106
|
}
|
|
107
107
|
type RuntimeIntegrationCategory = "gateway_remote_mcp" | "internal_mcp_credentials";
|
|
108
|
-
type RuntimeIntegrationConnectType = "oauth" | "credentials" | "none";
|
|
108
|
+
type RuntimeIntegrationConnectType = "oauth" | "user_token" | "credentials" | "none";
|
|
109
109
|
interface RuntimeIntegrationRecord {
|
|
110
110
|
id: string;
|
|
111
111
|
name: string;
|
|
@@ -113,6 +113,9 @@ interface RuntimeIntegrationRecord {
|
|
|
113
113
|
category: RuntimeIntegrationCategory;
|
|
114
114
|
connectType: RuntimeIntegrationConnectType;
|
|
115
115
|
authMode?: "oauth" | "user_token" | "server_token" | "none";
|
|
116
|
+
tokenLabel?: string;
|
|
117
|
+
tokenHelpUrl?: string;
|
|
118
|
+
tokenPlaceholder?: string;
|
|
116
119
|
credentialSchema?: unknown;
|
|
117
120
|
requiresOauth?: boolean;
|
|
118
121
|
connection?: {
|
|
@@ -132,6 +135,7 @@ declare class KontextMcp {
|
|
|
132
135
|
private readonly config;
|
|
133
136
|
private readonly storage;
|
|
134
137
|
private readonly oauthProvider;
|
|
138
|
+
private readonly clientSessionId;
|
|
135
139
|
private transport;
|
|
136
140
|
private client;
|
|
137
141
|
private _isConnected;
|
package/dist/mcp/index.js
CHANGED
|
@@ -409,6 +409,7 @@ var KontextMcp = class {
|
|
|
409
409
|
config;
|
|
410
410
|
storage;
|
|
411
411
|
oauthProvider;
|
|
412
|
+
clientSessionId = typeof globalThis.crypto?.randomUUID === "function" ? globalThis.crypto.randomUUID() : `kontext-sdk-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
|
|
412
413
|
transport = null;
|
|
413
414
|
client = null;
|
|
414
415
|
_isConnected = false;
|
|
@@ -580,7 +581,22 @@ var KontextMcp = class {
|
|
|
580
581
|
const url = typeof item.url === "string" ? item.url : "";
|
|
581
582
|
if (!id || !url) return null;
|
|
582
583
|
const category = item.category === "internal_mcp_credentials" ? "internal_mcp_credentials" : "gateway_remote_mcp";
|
|
583
|
-
const
|
|
584
|
+
const rawConnectType = item.connectType;
|
|
585
|
+
if (typeof rawConnectType !== "string") {
|
|
586
|
+
throw new KontextError(
|
|
587
|
+
"Runtime integration connectType is required in API response.",
|
|
588
|
+
"kontext_runtime_integrations_invalid_response",
|
|
589
|
+
{ meta: { integrationId: id, connectType: rawConnectType } }
|
|
590
|
+
);
|
|
591
|
+
}
|
|
592
|
+
const connectType = rawConnectType === "credentials" || rawConnectType === "oauth" || rawConnectType === "user_token" || rawConnectType === "none" ? rawConnectType : null;
|
|
593
|
+
if (!connectType) {
|
|
594
|
+
throw new KontextError(
|
|
595
|
+
`Unknown runtime integration connectType "${rawConnectType}".`,
|
|
596
|
+
"kontext_runtime_integrations_invalid_response",
|
|
597
|
+
{ meta: { integrationId: id, connectType: rawConnectType } }
|
|
598
|
+
);
|
|
599
|
+
}
|
|
584
600
|
const rawConnection = item.connection && typeof item.connection === "object" ? item.connection : void 0;
|
|
585
601
|
const connected = rawConnection && typeof rawConnection.connected === "boolean" ? rawConnection.connected : false;
|
|
586
602
|
const status = rawConnection?.status === "connected" ? "connected" : "disconnected";
|
|
@@ -591,6 +607,9 @@ var KontextMcp = class {
|
|
|
591
607
|
category,
|
|
592
608
|
connectType,
|
|
593
609
|
authMode: item.authMode === "oauth" || item.authMode === "user_token" || item.authMode === "server_token" || item.authMode === "none" ? item.authMode : void 0,
|
|
610
|
+
tokenLabel: typeof item.tokenLabel === "string" ? item.tokenLabel : void 0,
|
|
611
|
+
tokenHelpUrl: typeof item.tokenHelpUrl === "string" ? item.tokenHelpUrl : void 0,
|
|
612
|
+
tokenPlaceholder: typeof item.tokenPlaceholder === "string" ? item.tokenPlaceholder : void 0,
|
|
594
613
|
credentialSchema: item.credentialSchema,
|
|
595
614
|
requiresOauth: typeof item.requiresOauth === "boolean" ? item.requiresOauth : void 0,
|
|
596
615
|
connection: rawConnection ? {
|
|
@@ -728,13 +747,14 @@ var KontextMcp = class {
|
|
|
728
747
|
if (this.config.onElicitationUrl) {
|
|
729
748
|
capabilities.elicitation = { url: {} };
|
|
730
749
|
}
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
750
|
+
const clientInfo = {
|
|
751
|
+
name: this.config.clientName ?? "kontext-sdk",
|
|
752
|
+
version: this.config.clientVersion ?? "0.0.1",
|
|
753
|
+
sessionId: this.clientSessionId
|
|
754
|
+
};
|
|
755
|
+
this.client = new Client(clientInfo, {
|
|
756
|
+
capabilities
|
|
757
|
+
});
|
|
738
758
|
if (this.config.onElicitationUrl) {
|
|
739
759
|
const onElicitationUrl = this.config.onElicitationUrl;
|
|
740
760
|
this.client.setRequestHandler(ElicitRequestSchema, async (request) => {
|