@kontext-dev/js-sdk 0.3.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/ai/index.cjs +12 -2
- package/dist/adapters/ai/index.cjs.map +1 -1
- package/dist/adapters/ai/index.js +12 -2
- package/dist/adapters/ai/index.js.map +1 -1
- package/dist/adapters/cloudflare/index.cjs +13 -0
- package/dist/adapters/cloudflare/index.cjs.map +1 -1
- package/dist/adapters/cloudflare/index.js +13 -0
- package/dist/adapters/cloudflare/index.js.map +1 -1
- package/dist/adapters/cloudflare/react.cjs +12 -2
- package/dist/adapters/cloudflare/react.cjs.map +1 -1
- package/dist/adapters/cloudflare/react.js +12 -2
- package/dist/adapters/cloudflare/react.js.map +1 -1
- package/dist/adapters/react/index.cjs +12 -2
- package/dist/adapters/react/index.cjs.map +1 -1
- package/dist/adapters/react/index.js +12 -2
- package/dist/adapters/react/index.js.map +1 -1
- package/dist/client/index.cjs +108 -69
- package/dist/client/index.cjs.map +1 -1
- package/dist/client/index.d.cts +2 -0
- package/dist/client/index.d.ts +2 -0
- package/dist/client/index.js +109 -71
- package/dist/client/index.js.map +1 -1
- package/dist/errors.cjs +78 -0
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.d.cts +7 -1
- package/dist/errors.d.ts +7 -1
- package/dist/errors.js +78 -1
- package/dist/errors.js.map +1 -1
- package/dist/index.cjs +151 -87
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +152 -88
- package/dist/index.js.map +1 -1
- package/dist/{kontext-CgIBANFo.d.cts → kontext-CBPuE-hq.d.cts} +3 -0
- package/dist/{kontext-CgIBANFo.d.ts → kontext-CBPuE-hq.d.ts} +3 -0
- package/dist/management/index.cjs +15 -0
- 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 +15 -1
- package/dist/management/index.js.map +1 -1
- package/dist/mcp/index.cjs +32 -3
- package/dist/mcp/index.cjs.map +1 -1
- package/dist/mcp/index.d.cts +7 -1
- package/dist/mcp/index.d.ts +7 -1
- package/dist/mcp/index.js +33 -4
- package/dist/mcp/index.js.map +1 -1
- package/dist/oauth/index.cjs +12 -2
- 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 +12 -2
- package/dist/oauth/index.js.map +1 -1
- package/dist/server/index.cjs +55 -20
- package/dist/server/index.cjs.map +1 -1
- package/dist/server/index.d.cts +2 -2
- package/dist/server/index.d.ts +2 -2
- package/dist/server/index.js +56 -21
- package/dist/server/index.js.map +1 -1
- package/dist/{types-CzhnlJHW.d.cts → types-DicGI7ix.d.cts} +23 -1
- package/dist/{types-CzhnlJHW.d.ts → types-DicGI7ix.d.ts} +23 -1
- package/package.json +1 -1
package/dist/client/index.js.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","../../src/client/tool-utils.ts","../../src/client/orchestrator/internal/backends.ts","../../src/client/orchestrator/internal/routes.ts","../../src/client/orchestrator/internal/inventory.ts","../../src/client/orchestrator/internal/policy.ts","../../src/client/orchestrator/internal/state.ts","../../src/client/orchestrator/token-manager.ts","../../src/client/orchestrator/internal-client-registry.ts","../../src/client/orchestrator/index.ts","../../src/client/index.ts"],"names":[],"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;AA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ACF;AAAA,KACF;AAAA,IAEA,EAAA,CACE,OAEA,OAAA,EACY;AACZ,MAAA,IAAI,CAAC,UAAA,CAAW,GAAA,CAAI,KAAK,CAAA,EAAG;AAC1B,QAAA,UAAA,CAAW,GAAA,CAAI,KAAA,kBAAO,IAAI,GAAA,EAAK,CAAA;AAAA,MACjC;AACA,MAAA,UAAA,CAAW,GAAA,CAAI,KAAK,CAAA,CAAG,GAAA,CAAI,OAAO,CAAA;AAClC,MAAA,OAAO,MAAM;AACX,QAAA,UAAA,CAAW,GAAA,CAAI,KAAK,CAAA,EAAG,MAAA,CAAO,OAAO,CAAA;AAAA,MACvC,CAAA;AAAA,IACF,CAAA;AAAA,IAEA,IAAI,GAAA,GAAM;AACR,MAAA,OAAO,GAAA;AAAA,IACT;AAAA,GACF;AAEA,EAAA,OAAO,MAAA;AACT;AAcO,SAAS,oBACd,MAAA,EACe;AACf,EAAA,IAAI,MAAA,CAAO,QAAQ,MAAA,EAAW;AAC5B,IAAA,IAAI,OAAO,OAAO,GAAA,KAAQ,QAAA,IAAY,OAAO,GAAA,CAAI,IAAA,EAAK,CAAE,MAAA,KAAW,CAAA,EAAG;AACpE,MAAA,MAAM,IAAI,WAAA;AAAA,QACR,+FAAA;AAAA,QACA;AAAA,OACF;AAAA,IACF;AACA,IAAA,OAAO,kCAAkC,MAAM,CAAA;AAAA,EACjD;AAEA,EAAA,OAAO,0BAA0B,MAAM,CAAA;AACzC","file":"index.js","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 = \"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 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 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 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","/**\n * Shared utilities for Kontext tool handling.\n * Used by both KontextClient (core) and withKontext (Cloudflare adapter).\n */\n\nimport {\n ConfigError,\n IntegrationConnectionRequiredError,\n type ElicitationEntry,\n} from \"../errors.js\";\n\n// Re-export for consumers that import this type from tool-utils.\nexport type { ElicitationEntry } from \"../errors.js\";\n\n// ============================================================================\n// Shared types\n// ============================================================================\n\nexport interface IntegrationStatus {\n readonly id: string;\n readonly name: string;\n readonly connected: boolean;\n readonly connectUrl?: string;\n}\n\n// ============================================================================\n// System prompt\n// ============================================================================\n\n/**\n * Build an LLM system prompt based on available tool names and integration status.\n * Detects `*_SEARCH_TOOLS` / `*_EXECUTE_TOOL` suffixed names from the\n * Cloudflare Agents MCP proxy and generates appropriate guidance.\n */\nexport function buildKontextSystemPrompt(\n toolNames: readonly string[],\n integrations: readonly IntegrationStatus[],\n): string {\n if (toolNames.length === 0) return \"\";\n\n const searchTool = toolNames.find(\n (n) => n.endsWith(\"_SEARCH_TOOLS\") || n === \"SEARCH_TOOLS\",\n );\n const executeTool = toolNames.find(\n (n) => n.endsWith(\"_EXECUTE_TOOL\") || n === \"EXECUTE_TOOL\",\n );\n const requestCapabilityTool = toolNames.find(\n (n) => n.endsWith(\"_REQUEST_CAPABILITY\") || n === \"REQUEST_CAPABILITY\",\n );\n\n let prompt =\n \"You are a helpful assistant with access to various tools and integrations through Kontext.\\n\" +\n \"You can help users with tasks across their connected services (GitHub, Linear, Slack, etc.).\\n\" +\n \"When a user asks about their services, use the available MCP tools to help them.\\n\" +\n \"The user has already authenticated — tools run as the user with their permissions, including access to private repositories and org resources.\\n\" +\n \"If a Kontext tool can satisfy an integration-related request, use the Kontext tool and do not use shell or CLI commands for that request.\\n\" +\n \"Use shell or CLI only when no relevant Kontext tool exists or when the user explicitly requests local shell actions.\";\n\n if (searchTool && executeTool) {\n prompt +=\n `\\n\\nYou have access to external integrations through Kontext MCP tools:\\n` +\n `- Call \\`${searchTool}\\` first to discover what tools/integrations are available.\\n` +\n `- Then call \\`${executeTool}\\` with the tool_id and arguments to run a specific tool.\\n` +\n `- When the user asks about \"my repos\", \"my issues\", etc., use the appropriate tool to look up their data directly. Do not ask for their username — the tools already know who they are.\\n` +\n `Always start by searching for tools when the user asks about their connected services.`;\n }\n\n // Append integration status section when there are integrations to report\n if (integrations.length > 0) {\n const connected = integrations.filter((i) => i.connected);\n const disconnected = integrations.filter((i) => !i.connected);\n\n if (disconnected.length > 0) {\n prompt += \"\\n\\n## Integration Status\";\n\n if (connected.length > 0) {\n prompt += `\\n\\nYou already have access to: ${connected.map((i) => i.name).join(\", \")}`;\n }\n\n prompt += `\\n\\nThe following services require user authorization: ${disconnected.map((i) => i.name).join(\", \")}`;\n\n if (requestCapabilityTool) {\n prompt +=\n `\\n\\n**IMPORTANT:** When the user requests an action that requires one of these services:` +\n `\\n1. Call the \\`${requestCapabilityTool}\\` tool` +\n `\\n2. The tool returns a fresh integrations management link` +\n `\\n3. Include the link in your response so the user can connect or manage integrations` +\n `\\n4. Always call the tool for a fresh link and never reuse a previously returned URL`;\n } else {\n prompt +=\n \"\\n\\nWhen the user asks about a disconnected integration, let them know it needs to be connected first. Do not attempt to use tools from disconnected integrations without informing the user.\";\n }\n } else if (requestCapabilityTool && connected.length > 0) {\n prompt +=\n \"\\n\\n## Integration Management\" +\n `\\n\\nIf the user asks to manage, reconnect, or verify integrations, call \\`${requestCapabilityTool}\\` to get a fresh integrations management link.`;\n }\n }\n\n return prompt;\n}\n\n// ============================================================================\n// Auth-aware toolset orchestrator\n// ============================================================================\n\nexport interface AuthAwareToolset {\n /** System prompt with integration status and REQUEST_CAPABILITY instructions. */\n readonly systemPrompt: string;\n /** REQUEST_CAPABILITY tool to inject, or null if all integrations are connected. */\n readonly requestCapabilityTool: {\n readonly name: string;\n readonly description: string;\n readonly parameters: Record<string, unknown>;\n readonly execute: () => Promise<string>;\n } | null;\n}\n\n/**\n * Enrich a tool set with auth awareness.\n *\n * Given tool names and integration status, produces:\n * - A system prompt that tells the LLM about connected/disconnected integrations\n * - A REQUEST_CAPABILITY tool (if needed) that returns a fresh management URL as text\n *\n * Both `ai/` and `cloudflare/` adapters use this as their core auth layer.\n */\nexport function enrichToolsWithAuthAwareness(\n toolNames: readonly string[],\n integrations: readonly IntegrationStatus[],\n options?: {\n prefix?: string;\n requireServerRequestCapability?: boolean;\n requestCapabilityProxy?: () => Promise<string>;\n },\n): AuthAwareToolset {\n const serverRequestCapability = toolNames.find(\n (name) =>\n name.endsWith(\"_REQUEST_CAPABILITY\") || name === \"REQUEST_CAPABILITY\",\n );\n\n if (options?.requireServerRequestCapability && !serverRequestCapability) {\n throw new ConfigError(\n \"REQUEST_CAPABILITY tool is required but not exposed by the MCP server. Deploy API and SDK in lockstep.\",\n \"kontext_config_missing_request_capability_tool\",\n );\n }\n\n let requestCapabilityTool: AuthAwareToolset[\"requestCapabilityTool\"] = null;\n let effectiveToolNames = [...toolNames];\n\n if (options?.requestCapabilityProxy) {\n const prefix =\n options.prefix ??\n toolNames\n .find((n) => n.endsWith(\"_SEARCH_TOOLS\"))\n ?.replace(/_SEARCH_TOOLS$/, \"\") ??\n \"kontext\";\n const toolName = `${prefix}_REQUEST_CAPABILITY`;\n const tool = buildRequestCapabilityTool(\n integrations,\n options.requestCapabilityProxy!,\n );\n requestCapabilityTool = { name: toolName, ...tool };\n effectiveToolNames = [...effectiveToolNames, toolName];\n }\n\n return {\n systemPrompt: buildKontextSystemPrompt(effectiveToolNames, integrations),\n requestCapabilityTool,\n };\n}\n\n// ============================================================================\n// Integration status parsing\n// ============================================================================\n\n/**\n * Parse integration status from gateway tool search results.\n * Extracts connected integrations from tools and disconnected from errors.\n */\nexport function parseIntegrationStatus(\n tools: ReadonlyArray<{ server?: { id?: string; name?: string } }>,\n errors: ReadonlyArray<{ serverId: string; serverName?: string }>,\n elicitations?: ReadonlyArray<{\n url: string;\n integrationId?: string;\n integrationName?: string;\n }>,\n): IntegrationStatus[] {\n const seen = new Set<string>();\n const result: IntegrationStatus[] = [];\n\n for (const t of tools) {\n const sid = t.server?.id;\n if (sid && !seen.has(sid)) {\n seen.add(sid);\n result.push({\n id: sid,\n name: t.server?.name ?? sid,\n connected: true,\n });\n }\n }\n\n for (const e of errors) {\n if (!seen.has(e.serverId)) {\n seen.add(e.serverId);\n const elicitation = elicitations?.find(\n (el) => el.integrationId === e.serverId,\n );\n result.push({\n id: e.serverId,\n name: e.serverName ?? e.serverId,\n connected: false,\n connectUrl: elicitation?.url,\n });\n }\n }\n\n return result;\n}\n\n// ============================================================================\n// Request capability tool\n// ============================================================================\n\n/**\n * Build a tool that lets the LLM request a fresh integrations management URL.\n * Returns the URL as text so the LLM can present it to the user.\n * No popups — the user clicks the link in the chat.\n */\nexport function buildRequestCapabilityTool(\n capabilities: readonly IntegrationStatus[],\n executeRequestCapability: () => Promise<string>,\n): {\n description: string;\n parameters: Record<string, unknown>;\n execute: () => Promise<string>;\n} {\n const connected = capabilities.filter((c) => c.connected);\n const disconnected = capabilities.filter((c) => !c.connected);\n const connectedList =\n connected.length > 0 ? connected.map((c) => c.name).join(\", \") : \"none\";\n const disconnectedList =\n disconnected.length > 0\n ? disconnected.map((c) => c.name).join(\", \")\n : \"none\";\n\n return {\n description:\n \"Request a fresh integrations management link from the Kontext server. \" +\n `Connected integrations: ${connectedList}. ` +\n `Disconnected integrations: ${disconnectedList}. ` +\n \"Always call this tool for a fresh link and never reuse an older link.\",\n parameters: {\n type: \"object\",\n properties: {},\n },\n execute: async (): Promise<string> => {\n return executeRequestCapability();\n },\n };\n}\n\n/**\n * Pre-flight integration status detection.\n * Calls SEARCH_TOOLS on raw (unwrapped) tools to detect connected/disconnected\n * integrations without triggering any popups or broadcasts.\n */\nexport async function preflightIntegrationStatus(\n tools: ToolSetLike,\n): Promise<IntegrationStatus[]> {\n const searchToolKey = Object.keys(tools).find((k) =>\n k.endsWith(\"_SEARCH_TOOLS\"),\n );\n if (!searchToolKey || !tools[searchToolKey]?.execute) return [];\n\n try {\n const result = await tools[searchToolKey].execute!({ limit: 100 });\n\n // Cloudflare getAITools() returns MCP CallToolResult objects, not strings.\n // Extract JSON text from either a plain string or a CallToolResult shape.\n let json: string | undefined;\n if (typeof result === \"string\") {\n json = result;\n } else if (result && typeof result === \"object\") {\n const content = (\n result as {\n content?: Array<{\n type: string;\n resource?: { text?: string };\n text?: string;\n }>;\n }\n ).content;\n const first = content?.[0];\n json = first?.resource?.text ?? first?.text;\n }\n\n if (typeof json === \"string\") {\n const parsed = JSON.parse(json);\n if (parsed && typeof parsed === \"object\") {\n return parseIntegrationStatus(\n Array.isArray(parsed.items) ? parsed.items : [],\n Array.isArray(parsed.errors) ? parsed.errors : [],\n Array.isArray(parsed.elicitations) ? parsed.elicitations : [],\n );\n }\n }\n } catch (err: unknown) {\n // All integrations disconnected: -32042 error contains elicitations\n const elicitations = extractElicitations(err);\n if (elicitations?.length) {\n return elicitations\n .filter(\n (e): e is ElicitationEntry & { integrationId: string } =>\n !!e.integrationId,\n )\n .map((e) => ({\n id: e.integrationId,\n name: e.integrationName ?? e.integrationId,\n connected: false,\n connectUrl: e.url,\n }));\n }\n }\n\n return [];\n}\n\n// ============================================================================\n// Tool wrapping\n// ============================================================================\n\n/** A tool with an optional async execute method */\nexport interface ToolLike {\n execute?: (...args: unknown[]) => Promise<unknown>;\n [key: string]: unknown;\n}\n\n/** Record of named tools */\nexport type ToolSetLike = Record<string, ToolLike>;\n\n/**\n * Extract elicitation entries from an error thrown by the MCP SDK.\n * Handles two shapes: direct code/data and nested cause.\n */\nexport function extractElicitations(\n err: unknown,\n): ElicitationEntry[] | undefined {\n const error = err as {\n code?: number;\n data?: { elicitations?: ElicitationEntry[] };\n cause?: {\n code?: number;\n data?: { elicitations?: ElicitationEntry[] };\n };\n };\n\n // Primary: structured McpError with code -32042\n if (error?.code === -32042 && error?.data?.elicitations?.length) {\n return error.data.elicitations;\n }\n\n // Nested cause (some SDK wrappers nest the original error)\n if (\n error?.cause?.code === -32042 &&\n error?.cause?.data?.elicitations?.length\n ) {\n return error.cause.data.elicitations;\n }\n\n return undefined;\n}\n\n/**\n * Wrap tools to catch MCP error code -32042 (URL elicitation required)\n * and convert to IntegrationConnectionRequiredError.\n */\nexport function wrapToolsWithElicitation<T extends ToolSetLike>(tools: T): T {\n return Object.fromEntries(\n Object.entries(tools).map(([name, tool]) => [\n name,\n {\n ...tool,\n execute: tool.execute\n ? async (...args: unknown[]) => {\n try {\n return await tool.execute!(...args);\n } catch (err: unknown) {\n const elicitations = extractElicitations(err);\n const elicitation = elicitations?.[0];\n if (elicitation?.url) {\n const integrationId = elicitation.integrationId ?? \"unknown\";\n throw new IntegrationConnectionRequiredError(integrationId, {\n integrationName: elicitation.integrationName,\n connectUrl: elicitation.url,\n message: elicitation.message,\n });\n }\n throw err;\n }\n }\n : undefined,\n },\n ]),\n ) as T;\n}\n","import type { KontextClient } from \"../../index.js\";\nimport type { RuntimeIntegrationRecord } from \"../../../mcp/client.js\";\n\nexport type BackendSource = \"gateway\" | \"internal\";\n\nexport interface RoutingBackend {\n backendId: string;\n source: BackendSource;\n client: KontextClient;\n integrationId?: string;\n integrationName?: string;\n}\n\nexport function gatewayBackendId(): \"gateway\" {\n return \"gateway\";\n}\n\nexport function internalBackendId(integrationId: string): string {\n return `internal:${integrationId}`;\n}\n\nexport function isInternalIntegration(\n integration: RuntimeIntegrationRecord,\n): boolean {\n return integration.category === \"internal_mcp_credentials\";\n}\n\nexport function sortInternalIntegrations(\n integrations: RuntimeIntegrationRecord[],\n): RuntimeIntegrationRecord[] {\n return integrations\n .filter(isInternalIntegration)\n .sort((a, b) => a.id.localeCompare(b.id));\n}\n\nexport function createGatewayBackend(client: KontextClient): RoutingBackend {\n return {\n backendId: gatewayBackendId(),\n source: \"gateway\",\n client,\n };\n}\n\nexport function createInternalBackend(input: {\n integration: RuntimeIntegrationRecord;\n client: KontextClient;\n}): RoutingBackend {\n return {\n backendId: internalBackendId(input.integration.id),\n source: \"internal\",\n client: input.client,\n integrationId: input.integration.id,\n integrationName: input.integration.name,\n };\n}\n","import type { KontextTool } from \"../../index.js\";\nimport type { BackendSource } from \"./backends.js\";\n\nexport interface ToolRouteRecord {\n toolId: string;\n backendId: string;\n source: BackendSource;\n backendToolId: string;\n integrationId?: string;\n}\n\nexport interface RouteInventoryCandidate {\n tool: KontextTool;\n route: ToolRouteRecord;\n}\n\nexport interface RouteConflictRecord {\n toolId: string;\n kept: ToolRouteRecord;\n dropped: ToolRouteRecord;\n}\n\nexport interface RouteInventorySnapshot {\n version: number;\n tools: KontextTool[];\n routes: Map<string, ToolRouteRecord>;\n conflicts: RouteConflictRecord[];\n}\n\nexport function emptyRouteInventorySnapshot(): RouteInventorySnapshot {\n return {\n version: 0,\n tools: [],\n routes: new Map(),\n conflicts: [],\n };\n}\n\nexport function buildRouteInventory(\n version: number,\n candidates: RouteInventoryCandidate[],\n options?: {\n onConflict?: (\n existing: ToolRouteRecord,\n incoming: ToolRouteRecord,\n ) => \"keep_existing\" | \"replace_existing\";\n },\n): RouteInventorySnapshot {\n const tools: KontextTool[] = [];\n const routes = new Map<string, ToolRouteRecord>();\n const conflicts: RouteConflictRecord[] = [];\n\n for (const candidate of candidates) {\n const toolId = candidate.route.toolId;\n if (!routes.has(toolId)) {\n routes.set(toolId, candidate.route);\n tools.push(candidate.tool);\n continue;\n }\n\n const existing = routes.get(toolId)!;\n const decision =\n options?.onConflict?.(existing, candidate.route) ?? \"keep_existing\";\n\n let kept = existing;\n let dropped = candidate.route;\n if (decision === \"replace_existing\") {\n const existingIdx = tools.findIndex((tool) => tool.id === toolId);\n if (existingIdx >= 0) {\n tools.splice(existingIdx, 1, candidate.tool);\n } else {\n tools.push(candidate.tool);\n }\n routes.set(toolId, candidate.route);\n kept = candidate.route;\n dropped = existing;\n }\n\n conflicts.push({\n toolId,\n kept,\n dropped,\n });\n }\n\n return {\n version,\n tools,\n routes,\n conflicts,\n };\n}\n","import {\n buildRouteInventory,\n emptyRouteInventorySnapshot,\n type RouteInventoryCandidate,\n type RouteInventorySnapshot,\n type ToolRouteRecord,\n} from \"./routes.js\";\n\nexport class RouteInventoryStore {\n private versionCounter = 0;\n private resetGeneration = 0;\n private buildRunCounter = 0;\n private latestCommittedBuildRun = 0;\n private snapshotState: RouteInventorySnapshot = emptyRouteInventorySnapshot();\n private pendingBuilds = new Map<string, Promise<RouteInventorySnapshot>>();\n\n get version(): number {\n return this.snapshotState.version;\n }\n\n get snapshot(): RouteInventorySnapshot {\n return this.snapshotState;\n }\n\n routeFor(toolId: string): ToolRouteRecord | undefined {\n return this.snapshotState.routes.get(toolId);\n }\n\n async build(\n buildCandidates: () => Promise<RouteInventoryCandidate[]>,\n options?: {\n key?: string;\n onConflict?: (\n existing: ToolRouteRecord,\n incoming: ToolRouteRecord,\n ) => \"keep_existing\" | \"replace_existing\";\n },\n ): Promise<RouteInventorySnapshot> {\n const key = options?.key ?? \"__default__\";\n const existingBuild = this.pendingBuilds.get(key);\n if (existingBuild) {\n return await existingBuild;\n }\n\n const buildGeneration = this.resetGeneration;\n const buildRun = ++this.buildRunCounter;\n const pendingPromise = (async () => {\n const candidates = await buildCandidates();\n if (this.resetGeneration !== buildGeneration) {\n return this.snapshotState;\n }\n if (buildRun >= this.latestCommittedBuildRun) {\n this.latestCommittedBuildRun = buildRun;\n this.versionCounter += 1;\n const snapshot = buildRouteInventory(this.versionCounter, candidates, {\n onConflict: options?.onConflict,\n });\n this.snapshotState = snapshot;\n return snapshot;\n }\n\n return buildRouteInventory(this.snapshotState.version, candidates, {\n onConflict: options?.onConflict,\n });\n })();\n this.pendingBuilds.set(key, pendingPromise);\n\n try {\n return await pendingPromise;\n } finally {\n if (this.pendingBuilds.get(key) === pendingPromise) {\n this.pendingBuilds.delete(key);\n }\n }\n }\n\n reset(): void {\n this.resetGeneration += 1;\n this.versionCounter = 0;\n this.latestCommittedBuildRun = this.buildRunCounter;\n this.snapshotState = emptyRouteInventorySnapshot();\n this.pendingBuilds.clear();\n }\n}\n","import { KontextError } from \"../../../errors.js\";\nimport type { ToolRouteRecord } from \"./routes.js\";\n\nexport interface RoutingPolicy {\n onRouteConflict(input: {\n toolId: string;\n existing: ToolRouteRecord;\n incoming: ToolRouteRecord;\n }): \"keep_existing\" | \"replace_existing\";\n}\n\nexport const defaultRoutingPolicy: RoutingPolicy = {\n onRouteConflict() {\n return \"keep_existing\";\n },\n};\n\nexport function toRouteConflictError(input: {\n toolId: string;\n kept: ToolRouteRecord;\n dropped: ToolRouteRecord;\n}): KontextError {\n return new KontextError(\n `Route conflict for tool \"${input.toolId}\". Keeping backend \"${input.kept.backendId}\" and dropping \"${input.dropped.backendId}\".`,\n \"kontext_tool_route_conflict\",\n {\n meta: {\n toolId: input.toolId,\n keptBackendId: input.kept.backendId,\n keptSource: input.kept.source,\n keptIntegrationId: input.kept.integrationId,\n droppedBackendId: input.dropped.backendId,\n droppedSource: input.dropped.source,\n droppedIntegrationId: input.dropped.integrationId,\n },\n },\n );\n}\n","import type { ClientState } from \"../../index.js\";\nimport type { KontextError } from \"../../../errors.js\";\n\nexport type KontextOrchestratorState = ClientState;\n\ntype OrchestratorEvent = \"stateChange\" | \"error\";\n\ntype ListenerMap = {\n stateChange: (state: KontextOrchestratorState) => void;\n error: (error: KontextError) => void;\n};\n\nexport interface OrchestratorStateController {\n readonly state: KontextOrchestratorState;\n setState(next: KontextOrchestratorState): void;\n emitError(error: KontextError): void;\n on(event: \"stateChange\", handler: ListenerMap[\"stateChange\"]): () => void;\n on(event: \"error\", handler: ListenerMap[\"error\"]): () => void;\n}\n\nexport function createOrchestratorStateController(input: {\n initialState?: KontextOrchestratorState;\n onStateChange?: (state: KontextOrchestratorState) => void;\n}): OrchestratorStateController {\n let state: KontextOrchestratorState = input.initialState ?? \"idle\";\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const listeners = new Map<OrchestratorEvent, Set<(...args: any[]) => void>>();\n\n function setState(next: KontextOrchestratorState): void {\n if (state === next) return;\n state = next;\n\n try {\n input.onStateChange?.(next);\n } catch {\n // Ignore user callback failures.\n }\n\n const handlers = listeners.get(\"stateChange\");\n if (!handlers) return;\n for (const handler of handlers) {\n try {\n handler(next);\n } catch {\n // Ignore listener failures.\n }\n }\n }\n\n function emitError(error: KontextError): void {\n const handlers = listeners.get(\"error\");\n if (!handlers) return;\n for (const handler of handlers) {\n try {\n handler(error);\n } catch {\n // Ignore listener failures.\n }\n }\n }\n\n function on(\n event: \"stateChange\" | \"error\",\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n handler: (...args: any[]) => void,\n ): () => void {\n if (!listeners.has(event)) {\n listeners.set(event, new Set());\n }\n listeners.get(event)!.add(handler);\n return () => {\n listeners.get(event)?.delete(handler);\n };\n }\n\n return {\n get state() {\n return state;\n },\n setState,\n emitError,\n on,\n };\n}\n","import { AuthorizationRequiredError, KontextError } from \"../../errors.js\";\nimport type { RuntimeIntegrationRecord } from \"../../mcp/client.js\";\nimport type { KontextStorage } from \"../../storage/types.js\";\nimport { createStorageKey, StorageKeys } from \"../../storage/types.js\";\n\ntype StoredAccessToken = {\n access_token?: string;\n expires_in?: number | string;\n issued_at?: number | string;\n token_type?: string;\n};\n\nfunction hasFreshStoredToken(\n tokens: StoredAccessToken | undefined,\n skewMs = 30_000,\n): boolean {\n if (!tokens?.access_token) return false;\n const expiresIn =\n typeof tokens.expires_in === \"number\"\n ? tokens.expires_in\n : Number(tokens.expires_in);\n const issuedAt =\n typeof tokens.issued_at === \"number\"\n ? tokens.issued_at\n : Number(tokens.issued_at);\n\n if (!Number.isFinite(expiresIn) || !Number.isFinite(issuedAt)) {\n return false;\n }\n\n const expiresAt = issuedAt + expiresIn * 1000;\n return Date.now() + skewMs < expiresAt;\n}\n\nexport interface TokenManager {\n tokenStorageKey(sessionKey: string): string;\n ensureInternalResourceToken(\n integration: RuntimeIntegrationRecord,\n options?: { forceExchange?: boolean },\n ): Promise<void>;\n}\n\nexport function createTokenManager(input: {\n clientId: string;\n baseSessionKey: string;\n gatewaySessionKey: string;\n serverUrl: string;\n storage: KontextStorage;\n}): TokenManager {\n const pendingInternalTokenExchange = new Map<string, Promise<void>>();\n\n function tokenStorageKey(sessionKey: string): string {\n return createStorageKey(input.clientId, sessionKey, StorageKeys.TOKENS);\n }\n\n async function readGatewayTokens(): Promise<{\n subjectToken: string | null;\n }> {\n const identityTokens = await input.storage.getJson<{\n access_token?: string;\n }>(\n createStorageKey(\n input.clientId,\n input.gatewaySessionKey,\n StorageKeys.IDENTITY_TOKENS,\n ),\n );\n const gatewayTokens = await input.storage.getJson<{\n access_token?: string;\n }>(tokenStorageKey(input.gatewaySessionKey));\n\n return {\n subjectToken:\n identityTokens?.access_token ?? gatewayTokens?.access_token ?? null,\n };\n }\n\n async function ensureInternalResourceToken(\n integration: RuntimeIntegrationRecord,\n options?: { forceExchange?: boolean },\n ): Promise<void> {\n const internalSessionKey = `${input.baseSessionKey}:internal:${integration.id}`;\n if (!options?.forceExchange) {\n const existingToken = await input.storage.getJson<StoredAccessToken>(\n tokenStorageKey(internalSessionKey),\n );\n if (hasFreshStoredToken(existingToken)) {\n return;\n }\n }\n\n const pending = pendingInternalTokenExchange.get(integration.id);\n if (pending) {\n return await pending;\n }\n\n const exchangePromise = (async () => {\n const { subjectToken: gatewaySubjectToken } = await readGatewayTokens();\n if (!gatewaySubjectToken) {\n return;\n }\n\n const body = new URLSearchParams({\n grant_type: \"urn:ietf:params:oauth:grant-type:token-exchange\",\n subject_token_type: \"urn:ietf:params:oauth:token-type:access_token\",\n subject_token: gatewaySubjectToken,\n resource: integration.url,\n client_id: input.clientId,\n });\n\n const response = await fetch(`${input.serverUrl}/oauth2/token`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n },\n body: body.toString(),\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 exchange gateway token for internal resource \"${integration.id}\": HTTP ${response.status}`,\n \"kontext_token_exchange_failed\",\n {\n statusCode: response.status,\n meta: {\n integrationId: integration.id,\n resource: integration.url,\n },\n },\n );\n }\n\n const exchanged = (await response.json()) as {\n access_token?: string;\n token_type?: string;\n expires_in?: number;\n refresh_token?: string;\n scope?: string;\n };\n\n if (!exchanged.access_token || !exchanged.token_type) {\n throw new KontextError(\n `Token exchange returned an invalid payload for integration \"${integration.id}\".`,\n \"kontext_token_exchange_failed\",\n {\n meta: {\n integrationId: integration.id,\n resource: integration.url,\n },\n },\n );\n }\n\n await input.storage.setJson(tokenStorageKey(internalSessionKey), {\n ...exchanged,\n issued_at: Date.now(),\n });\n })();\n\n pendingInternalTokenExchange.set(integration.id, exchangePromise);\n try {\n await exchangePromise;\n } finally {\n pendingInternalTokenExchange.delete(integration.id);\n }\n }\n\n return {\n tokenStorageKey,\n ensureInternalResourceToken,\n };\n}\n","import type { KontextClient } from \"../index.js\";\nimport type { RuntimeIntegrationRecord } from \"../../mcp/client.js\";\nimport {\n sortInternalIntegrations,\n type RoutingBackend,\n} from \"./internal/backends.js\";\n\nexport type InternalClientEntry = {\n integration: RuntimeIntegrationRecord;\n backendId: string;\n client: KontextClient;\n unsubscribeState: () => void;\n unsubscribeError: () => void;\n};\n\ntype InternalClientFactoryResult = {\n backend: RoutingBackend;\n client: KontextClient;\n unsubscribeState: () => void;\n unsubscribeError: () => void;\n};\n\nexport interface InternalClientRegistry {\n readonly size: number;\n entries(): IterableIterator<[string, InternalClientEntry]>;\n values(): IterableIterator<InternalClientEntry>;\n keys(): IterableIterator<string>;\n get(integrationId: string): InternalClientEntry | undefined;\n sync(discovered: RuntimeIntegrationRecord[]): Promise<void>;\n missingResolved(resolvedIntegrations: Set<string>): string[];\n dispose(mode: \"disconnect\" | \"signOut\"): Promise<void>;\n}\n\nexport function createInternalClientRegistry(input: {\n backends: Map<string, RoutingBackend>;\n createClient: (\n integration: RuntimeIntegrationRecord,\n ) => InternalClientFactoryResult;\n}): InternalClientRegistry {\n const internalClients = new Map<string, InternalClientEntry>();\n\n async function remove(integrationId: string): Promise<void> {\n const existing = internalClients.get(integrationId);\n if (!existing) return;\n\n existing.unsubscribeState();\n existing.unsubscribeError();\n internalClients.delete(integrationId);\n input.backends.delete(existing.backendId);\n\n try {\n await existing.client.disconnect();\n } catch {\n // Best effort disconnect.\n }\n }\n\n async function sync(discovered: RuntimeIntegrationRecord[]): Promise<void> {\n const sortedInternal = sortInternalIntegrations(discovered);\n const desiredById = new Map(sortedInternal.map((item) => [item.id, item]));\n\n for (const [integrationId, existing] of internalClients) {\n const next = desiredById.get(integrationId);\n if (!next) {\n await remove(integrationId);\n continue;\n }\n\n if (existing.integration.url !== next.url) {\n await remove(integrationId);\n }\n }\n\n for (const integration of sortedInternal) {\n const existing = internalClients.get(integration.id);\n if (existing) {\n existing.integration = integration;\n\n const backend = input.backends.get(existing.backendId);\n if (backend) {\n backend.integrationName = integration.name;\n }\n continue;\n }\n\n const created = input.createClient(integration);\n input.backends.set(created.backend.backendId, created.backend);\n internalClients.set(integration.id, {\n integration,\n backendId: created.backend.backendId,\n client: created.client,\n unsubscribeState: created.unsubscribeState,\n unsubscribeError: created.unsubscribeError,\n });\n }\n }\n\n function missingResolved(resolvedIntegrations: Set<string>): string[] {\n const missing: string[] = [];\n for (const integrationId of internalClients.keys()) {\n if (!resolvedIntegrations.has(integrationId)) {\n missing.push(integrationId);\n }\n }\n return missing;\n }\n\n async function dispose(mode: \"disconnect\" | \"signOut\"): Promise<void> {\n const entries = [...internalClients.values()];\n internalClients.clear();\n\n for (const backend of [...input.backends.values()]) {\n if (backend.source === \"internal\") {\n input.backends.delete(backend.backendId);\n }\n }\n\n await Promise.all(\n entries.map(async (entry) => {\n entry.unsubscribeState();\n entry.unsubscribeError();\n try {\n if (mode === \"signOut\") {\n await entry.client.auth.signOut();\n } else {\n await entry.client.disconnect();\n }\n } catch {\n // Best effort shutdown.\n }\n }),\n );\n }\n\n return {\n get size() {\n return internalClients.size;\n },\n entries() {\n return internalClients.entries();\n },\n values() {\n return internalClients.values();\n },\n keys() {\n return internalClients.keys();\n },\n get(integrationId: string) {\n return internalClients.get(integrationId);\n },\n sync,\n missingResolved,\n dispose,\n };\n}\n","/**\n * KontextOrchestrator — unified mixed-mode client facade.\n *\n * Combines:\n * - Gateway-routed tools (gateway_remote_mcp)\n * - Direct internal MCP tools (internal_mcp_credentials)\n *\n * into a single tool listing/execution surface.\n */\n\nimport {\n createSingleEndpointKontextClient,\n type ConnectSessionResult,\n type IntegrationInfo,\n type KontextClient,\n type KontextClientConfig,\n type KontextTool,\n type ToolResult,\n} from \"../index.js\";\nimport {\n normalizeKontextServerUrl,\n type RuntimeIntegrationRecord,\n} from \"../../mcp/client.js\";\nimport { MemoryStorage } from \"../../storage/memory.js\";\nimport type { KontextStorage } from \"../../storage/types.js\";\nimport {\n AuthorizationRequiredError,\n ConfigError,\n KontextError,\n isKontextError,\n isNetworkError,\n isUnauthorizedError,\n} from \"../../errors.js\";\nimport {\n createGatewayBackend,\n createInternalBackend,\n gatewayBackendId,\n internalBackendId,\n type RoutingBackend,\n} from \"./internal/backends.js\";\nimport { RouteInventoryStore } from \"./internal/inventory.js\";\nimport type {\n RouteConflictRecord,\n RouteInventoryCandidate,\n ToolRouteRecord,\n} from \"./internal/routes.js\";\nimport {\n defaultRoutingPolicy,\n toRouteConflictError,\n} from \"./internal/policy.js\";\nimport {\n createOrchestratorStateController,\n type KontextOrchestratorState,\n} from \"./internal/state.js\";\nimport { createTokenManager } from \"./token-manager.js\";\nimport {\n createInternalClientRegistry,\n type InternalClientEntry,\n} from \"./internal-client-registry.js\";\n\nexport type { KontextOrchestratorState };\n\nexport interface KontextOrchestratorConfig {\n clientId: string;\n redirectUri: string;\n serverUrl?: string;\n storage?: KontextStorage;\n sessionKey?: string;\n onAuthRequired: KontextClientConfig[\"onAuthRequired\"];\n onIntegrationRequired?: KontextClientConfig[\"onIntegrationRequired\"];\n onStateChange?: (state: KontextOrchestratorState) => void;\n}\n\nexport interface KontextOrchestrator {\n readonly state: KontextOrchestratorState;\n\n connect(): Promise<void>;\n disconnect(): Promise<void>;\n getConnectPageUrl(): Promise<ConnectSessionResult>;\n\n readonly auth: {\n signIn(): Promise<void>;\n signOut(): Promise<void>;\n handleCallback(url: string | URL): Promise<void>;\n isCallback(url: string | URL): boolean;\n readonly isAuthenticated: boolean;\n };\n\n readonly integrations: {\n list(): Promise<IntegrationInfo[]>;\n };\n\n readonly tools: {\n list(options?: { limit?: number }): Promise<KontextTool[]>;\n execute(\n toolId: string,\n args?: Record<string, unknown>,\n ): Promise<ToolResult>;\n };\n\n on(\n event: \"stateChange\",\n handler: (state: KontextOrchestratorState) => void,\n ): () => void;\n on(event: \"error\", handler: (error: KontextError) => void): () => void;\n\n readonly mcp: KontextClient[\"mcp\"];\n}\n\ntype ErrorContext = {\n backendId?: string;\n source?: \"gateway\" | \"internal\";\n integrationId?: string;\n operation: string;\n toolId?: string;\n};\n\nfunction isTransientError(err: unknown): boolean {\n if (err instanceof Error && isNetworkError(err)) {\n return true;\n }\n\n if (isKontextError(err)) {\n if (err.code === \"kontext_network_error\") return true;\n if (err.statusCode === 429) return true;\n if (typeof err.statusCode === \"number\" && err.statusCode >= 500) {\n return true;\n }\n return false;\n }\n\n if (typeof err === \"object\" && err !== null) {\n const errObj = err as { status?: unknown; statusCode?: unknown };\n const maybeStatus = errObj.statusCode ?? errObj.status;\n const status = typeof maybeStatus === \"number\" ? maybeStatus : undefined;\n if (status === 429 || (typeof status === \"number\" && status >= 500)) {\n return true;\n }\n }\n\n return false;\n}\n\nasync function withTransientRetry<T>(\n operation: () => Promise<T>,\n maxRetries = 1,\n): Promise<T> {\n const retryDelayMs = 250;\n for (let attempt = 0; attempt <= maxRetries; attempt += 1) {\n try {\n return await operation();\n } catch (err) {\n if (attempt >= maxRetries || !isTransientError(err)) {\n throw err;\n }\n await new Promise((resolve) => setTimeout(resolve, retryDelayMs));\n }\n }\n\n throw new Error(\"Transient retry loop exhausted unexpectedly.\");\n}\n\nfunction toKontextError(err: unknown, context?: ErrorContext): KontextError {\n const contextMeta = context ? { ...context } : undefined;\n const mergeMeta = (\n base?: Record<string, unknown>,\n ): Record<string, unknown> =>\n contextMeta ? { ...(base ?? {}), ...contextMeta } : (base ?? {});\n\n if (isKontextError(err)) {\n if (!contextMeta) {\n return err;\n }\n\n // Preserve subclass identity and specialized fields while avoiding\n // in-place mutation of shared error instances.\n const cloned = Object.create(Object.getPrototypeOf(err)) as KontextError;\n Object.defineProperties(cloned, Object.getOwnPropertyDescriptors(err));\n Object.defineProperty(cloned, \"meta\", {\n value: mergeMeta(err.meta),\n enumerable: true,\n writable: true,\n configurable: true,\n });\n return cloned;\n }\n\n if (err instanceof Error) {\n if (isUnauthorizedError(err)) {\n return new AuthorizationRequiredError(err.message, {\n meta: mergeMeta(),\n cause: err,\n });\n }\n return new KontextError(err.message, \"kontext_unknown_error\", {\n meta: mergeMeta(),\n cause: err,\n });\n }\n\n return new KontextError(String(err), \"kontext_unknown_error\", {\n meta: mergeMeta(),\n });\n}\n\nfunction isAuthorizationRequired(err: unknown): boolean {\n if (err instanceof AuthorizationRequiredError) return true;\n if (isKontextError(err)) {\n return err.code === \"kontext_authorization_required\";\n }\n if (typeof err === \"object\" && err !== null) {\n return (\n (err as { code?: unknown }).code === \"kontext_authorization_required\"\n );\n }\n return false;\n}\n\nfunction isTokenExchangeFailure(err: unknown): boolean {\n if (isKontextError(err)) {\n return err.code === \"kontext_token_exchange_failed\";\n }\n if (typeof err === \"object\" && err !== null) {\n return (err as { code?: unknown }).code === \"kontext_token_exchange_failed\";\n }\n return false;\n}\n\nfunction isAuthRecoveryRequired(err: unknown): boolean {\n return isAuthorizationRequired(err) || isTokenExchangeFailure(err);\n}\nexport function createKontextOrchestrator(\n config: KontextOrchestratorConfig,\n): KontextOrchestrator {\n if (!config.clientId) {\n throw new ConfigError(\n \"clientId is required. Pass it in KontextOrchestratorConfig.\",\n \"kontext_config_missing_client_id\",\n );\n }\n if (!config.redirectUri) {\n throw new ConfigError(\n \"redirectUri is required. Set it to the URL where OAuth should redirect after authorization.\",\n \"kontext_config_missing_redirect_uri\",\n );\n }\n if (!config.onAuthRequired) {\n throw new ConfigError(\n \"onAuthRequired callback is required. Provide a function that opens the OAuth URL.\",\n \"kontext_config_missing_auth_handler\",\n );\n }\n\n const baseSessionKey = config.sessionKey ?? \"default\";\n const serverUrl = normalizeKontextServerUrl(\n config.serverUrl ?? \"https://api.kontext.dev\",\n );\n const sharedStorage = config.storage ?? new MemoryStorage();\n const gatewaySessionKey = `${baseSessionKey}:gateway`;\n\n const authSourceQueue: Array<\"gateway\" | string> = [];\n const stateController = createOrchestratorStateController({\n initialState: \"idle\",\n onStateChange: config.onStateChange,\n });\n\n const routeInventory = new RouteInventoryStore();\n const routingPolicy = defaultRoutingPolicy;\n\n const runtimeIntegrations = new Map<string, RuntimeIntegrationRecord>();\n const backends = new Map<string, RoutingBackend>();\n const managedInternalOps = new Map<string, number>();\n const resolvedInternalListings = new Set<string>();\n\n const tokenManager = createTokenManager({\n clientId: config.clientId,\n baseSessionKey,\n gatewaySessionKey,\n serverUrl,\n storage: sharedStorage,\n });\n\n let pendingIntegrationRefresh: Promise<RuntimeIntegrationRecord[]> | null =\n null;\n\n const gatewayClient = createSingleEndpointKontextClient({\n clientId: config.clientId,\n redirectUri: config.redirectUri,\n serverUrl: config.serverUrl,\n storage: sharedStorage,\n sessionKey: gatewaySessionKey,\n onAuthRequired: async (url) => {\n authSourceQueue.push(\"gateway\");\n return await config.onAuthRequired(url);\n },\n onIntegrationRequired: config.onIntegrationRequired,\n });\n\n const gatewayBackend = createGatewayBackend(gatewayClient);\n backends.set(gatewayBackendId(), gatewayBackend);\n\n const gatewayStateUnsubscribe = gatewayClient.on(\"stateChange\", (state) => {\n if (state === \"needs_auth\") {\n stateController.setState(\"needs_auth\");\n }\n });\n const gatewayErrorUnsubscribe = gatewayClient.on(\"error\", (error) => {\n const translated = toKontextError(error, {\n backendId: gatewayBackendId(),\n source: \"gateway\",\n operation: \"client_error_event\",\n });\n stateController.emitError(translated);\n if (isAuthRecoveryRequired(translated)) {\n stateController.setState(\"needs_auth\");\n }\n });\n\n const ensureInternalResourceToken = tokenManager.ensureInternalResourceToken;\n\n function isInternalOpManaged(integrationId: string): boolean {\n return (managedInternalOps.get(integrationId) ?? 0) > 0;\n }\n\n async function runManagedInternalOp<T>(\n integrationId: string,\n operation: () => Promise<T>,\n ): Promise<T> {\n managedInternalOps.set(\n integrationId,\n (managedInternalOps.get(integrationId) ?? 0) + 1,\n );\n try {\n return await operation();\n } finally {\n const next = (managedInternalOps.get(integrationId) ?? 1) - 1;\n if (next <= 0) {\n managedInternalOps.delete(integrationId);\n } else {\n managedInternalOps.set(integrationId, next);\n }\n }\n }\n\n function createInternalClient(integration: RuntimeIntegrationRecord): {\n backend: RoutingBackend;\n client: KontextClient;\n unsubscribeState: () => void;\n unsubscribeError: () => void;\n } {\n const client = createSingleEndpointKontextClient({\n clientId: config.clientId,\n redirectUri: config.redirectUri,\n url: integration.url,\n serverUrl: config.serverUrl,\n storage: sharedStorage,\n sessionKey: `${baseSessionKey}:internal:${integration.id}`,\n onAuthRequired: async (url) => {\n authSourceQueue.push(integration.id);\n return await config.onAuthRequired(url);\n },\n onIntegrationRequired: config.onIntegrationRequired,\n });\n\n const unsubscribeState = client.on(\"stateChange\", (state) => {\n if (state === \"needs_auth\") {\n stateController.setState(\"needs_auth\");\n }\n });\n const unsubscribeError = client.on(\"error\", (error) => {\n const translated = toKontextError(error, {\n backendId: internalBackendId(integration.id),\n source: \"internal\",\n integrationId: integration.id,\n operation: \"client_error_event\",\n });\n if (\n isInternalOpManaged(integration.id) &&\n isAuthorizationRequired(translated)\n ) {\n return;\n }\n if (isAuthRecoveryRequired(translated)) {\n stateController.setState(\"needs_auth\");\n return;\n }\n stateController.emitError(translated);\n });\n\n const backend = createInternalBackend({ integration, client });\n\n return { backend, client, unsubscribeState, unsubscribeError };\n }\n\n const internalClientRegistry = createInternalClientRegistry({\n backends,\n createClient: createInternalClient,\n });\n\n async function refreshIntegrationInventory(\n force = false,\n ): Promise<RuntimeIntegrationRecord[]> {\n if (pendingIntegrationRefresh) {\n if (!force) {\n return await pendingIntegrationRefresh;\n }\n // Serialize forced refreshes to avoid concurrent shared-state updates.\n await pendingIntegrationRefresh;\n }\n\n const refreshPromise = (async () => {\n const items = await withTransientRetry(\n async () => await gatewayClient.mcp.listRuntimeIntegrations(),\n );\n await applyRuntimeIntegrations(items);\n return items;\n })();\n pendingIntegrationRefresh = refreshPromise;\n\n try {\n return await refreshPromise;\n } finally {\n if (pendingIntegrationRefresh === refreshPromise) {\n pendingIntegrationRefresh = null;\n }\n }\n }\n\n async function applyRuntimeIntegrations(\n integrations: RuntimeIntegrationRecord[],\n ): Promise<void> {\n runtimeIntegrations.clear();\n for (const item of integrations) {\n runtimeIntegrations.set(item.id, item);\n }\n await internalClientRegistry.sync(integrations);\n }\n\n async function buildInventoryCandidates(options?: {\n limit?: number;\n runtimeIntegrations?: RuntimeIntegrationRecord[];\n }): Promise<RouteInventoryCandidate[]> {\n const candidates: RouteInventoryCandidate[] = [];\n resolvedInternalListings.clear();\n const pendingInternalAuthRetries = new Set<string>();\n\n const gatewayTools = await gatewayClient.tools.list(options);\n for (const tool of gatewayTools) {\n candidates.push({\n tool,\n route: {\n toolId: tool.id,\n backendId: gatewayBackendId(),\n source: \"gateway\",\n backendToolId: tool.id,\n },\n });\n }\n\n if (options?.runtimeIntegrations) {\n await applyRuntimeIntegrations(options.runtimeIntegrations);\n } else {\n await refreshIntegrationInventory();\n }\n\n const sortedInternalEntries = [...internalClientRegistry.values()].sort(\n (a, b) => a.integration.id.localeCompare(b.integration.id),\n );\n\n const addInternalToolsForEntry = async (entry: InternalClientEntry) => {\n const internalTools = await withTransientRetry(\n async () =>\n await runManagedInternalOp(entry.integration.id, () =>\n entry.client.tools.list(),\n ),\n );\n resolvedInternalListings.add(entry.integration.id);\n for (const tool of internalTools) {\n const backendToolId = tool.id || tool.name;\n const unifiedId = `${entry.integration.id}:${tool.name}`;\n\n candidates.push({\n tool: {\n id: unifiedId,\n name: tool.name,\n description: tool.description,\n inputSchema: tool.inputSchema,\n server: {\n id: entry.integration.id,\n name: entry.integration.name,\n },\n },\n route: {\n toolId: unifiedId,\n backendId: entry.backendId,\n source: \"internal\",\n backendToolId,\n integrationId: entry.integration.id,\n },\n });\n }\n };\n\n for (const entry of sortedInternalEntries) {\n try {\n await ensureInternalResourceToken(entry.integration);\n await addInternalToolsForEntry(entry);\n } catch (err) {\n const translated = toKontextError(err, {\n backendId: entry.backendId,\n source: \"internal\",\n integrationId: entry.integration.id,\n operation: \"tools.list\",\n });\n if (isAuthorizationRequired(translated)) {\n pendingInternalAuthRetries.add(entry.integration.id);\n continue;\n }\n if (isTokenExchangeFailure(translated)) {\n stateController.setState(\"needs_auth\");\n }\n stateController.emitError(translated);\n }\n }\n\n if (pendingInternalAuthRetries.size > 0) {\n let hasUnresolvedAuth = false;\n for (const integrationId of pendingInternalAuthRetries) {\n const entry = internalClientRegistry.get(integrationId);\n if (!entry) continue;\n\n try {\n await ensureInternalResourceToken(entry.integration, {\n forceExchange: true,\n });\n await runManagedInternalOp(integrationId, async () => {\n await entry.client.disconnect();\n await entry.client.connect();\n });\n await addInternalToolsForEntry(entry);\n } catch (err) {\n const translated = toKontextError(err);\n if (isAuthRecoveryRequired(translated)) {\n hasUnresolvedAuth = true;\n if (isTokenExchangeFailure(translated)) {\n stateController.emitError(translated);\n }\n continue;\n }\n stateController.emitError(translated);\n }\n }\n\n if (hasUnresolvedAuth) {\n stateController.setState(\"needs_auth\");\n } else if (\n stateController.state === \"needs_auth\" &&\n gatewayClient.state === \"ready\"\n ) {\n stateController.setState(\"ready\");\n }\n }\n\n return candidates;\n }\n\n async function buildToolInventory(options?: {\n limit?: number;\n runtimeIntegrations?: RuntimeIntegrationRecord[];\n }): Promise<{\n tools: KontextTool[];\n conflicts: RouteConflictRecord[];\n }> {\n const inventoryKey = JSON.stringify({\n limit: options?.limit ?? null,\n runtimeIntegrations:\n options?.runtimeIntegrations\n ?.map((integration) => integration.id)\n .sort() ?? null,\n });\n const snapshot = await routeInventory.build(\n async () => await buildInventoryCandidates(options),\n {\n key: inventoryKey,\n onConflict: (existing, incoming) =>\n routingPolicy.onRouteConflict({\n toolId: existing.toolId,\n existing,\n incoming,\n }),\n },\n );\n return {\n tools: snapshot.tools,\n conflicts: snapshot.conflicts,\n };\n }\n\n function emitRouteConflicts(conflicts: RouteConflictRecord[]): void {\n for (const conflict of conflicts) {\n stateController.emitError(\n toRouteConflictError({\n toolId: conflict.toolId,\n kept: conflict.kept,\n dropped: conflict.dropped,\n }),\n );\n }\n }\n\n function getInternalIntegrationsMissingTools(): string[] {\n return internalClientRegistry.missingResolved(resolvedInternalListings);\n }\n\n async function disposeInternalClients(\n mode: \"disconnect\" | \"signOut\",\n ): Promise<void> {\n await internalClientRegistry.dispose(mode);\n }\n\n async function ensureConnected(): Promise<void> {\n if (stateController.state === \"ready\") return;\n if (\n stateController.state === \"needs_auth\" &&\n gatewayClient.state === \"ready\"\n ) {\n return;\n }\n\n stateController.setState(\"connecting\");\n\n try {\n await gatewayClient.connect();\n await refreshIntegrationInventory(true);\n stateController.setState(\"ready\");\n } catch (err) {\n const translated = toKontextError(err, {\n backendId: gatewayBackendId(),\n source: \"gateway\",\n operation: \"connect\",\n });\n if (isAuthRecoveryRequired(translated)) {\n stateController.setState(\"needs_auth\");\n } else {\n stateController.setState(\"failed\");\n }\n stateController.emitError(translated);\n throw translated;\n }\n }\n\n async function routeForExecution(toolId: string): Promise<ToolRouteRecord> {\n let route = routeInventory.routeFor(toolId);\n if (route) return route;\n\n const inventory = await buildToolInventory();\n emitRouteConflicts(inventory.conflicts);\n route = routeInventory.routeFor(toolId);\n if (route) return route;\n\n throw new KontextError(\n `Unknown tool \"${toolId}\". Call tools.list() to refresh available tools.`,\n \"kontext_tool_not_found\",\n { meta: { toolId } },\n );\n }\n\n const orchestrator: KontextOrchestrator = {\n get state() {\n return stateController.state;\n },\n\n async connect() {\n await ensureConnected();\n },\n\n async disconnect() {\n await disposeInternalClients(\"disconnect\");\n runtimeIntegrations.clear();\n routeInventory.reset();\n authSourceQueue.length = 0;\n await gatewayClient.disconnect();\n stateController.setState(\"idle\");\n },\n\n async getConnectPageUrl(): Promise<ConnectSessionResult> {\n await ensureConnected();\n return await gatewayClient.getConnectPageUrl();\n },\n\n auth: {\n async signIn() {\n if (\n stateController.state === \"needs_auth\" &&\n gatewayClient.state === \"ready\"\n ) {\n await refreshIntegrationInventory(true);\n\n let unresolvedInternalAuth = false;\n for (const [\n integrationId,\n entry,\n ] of internalClientRegistry.entries()) {\n try {\n await runManagedInternalOp(integrationId, () =>\n entry.client.auth.signIn(),\n );\n } catch (err) {\n const translated = toKontextError(err);\n if (isAuthorizationRequired(translated)) {\n unresolvedInternalAuth = true;\n continue;\n }\n stateController.emitError(translated);\n }\n }\n\n const inventory = await buildToolInventory();\n emitRouteConflicts(inventory.conflicts);\n const missingInternal = getInternalIntegrationsMissingTools();\n if (!unresolvedInternalAuth && missingInternal.length === 0) {\n stateController.setState(\"ready\");\n }\n return;\n }\n\n await ensureConnected();\n },\n\n async signOut() {\n await disposeInternalClients(\"signOut\");\n runtimeIntegrations.clear();\n routeInventory.reset();\n authSourceQueue.length = 0;\n await gatewayClient.auth.signOut();\n stateController.setState(\"idle\");\n },\n\n async handleCallback(url: string | URL) {\n if (internalClientRegistry.size === 0) {\n try {\n await refreshIntegrationInventory(true);\n } catch (err) {\n stateController.emitError(\n toKontextError(err, {\n backendId: gatewayBackendId(),\n source: \"gateway\",\n operation: \"auth.handleCallback.preload\",\n }),\n );\n }\n }\n\n const ordered: Array<{\n client: KontextClient;\n sourceId?: \"gateway\" | string;\n }> = [];\n\n for (const sourceId of authSourceQueue) {\n if (sourceId === \"gateway\") {\n ordered.push({ client: gatewayClient, sourceId });\n continue;\n }\n const active = internalClientRegistry.get(sourceId);\n if (active) {\n ordered.push({ client: active.client, sourceId });\n }\n }\n\n if (gatewayClient.auth.isCallback(url)) {\n ordered.push({ client: gatewayClient });\n }\n\n for (const entry of internalClientRegistry.values()) {\n if (entry.client.auth.isCallback(url)) {\n ordered.push({ client: entry.client });\n }\n }\n\n ordered.push({ client: gatewayClient });\n ordered.push(\n ...[...internalClientRegistry.values()]\n .sort((a, b) => a.integration.id.localeCompare(b.integration.id))\n .map((entry) => ({ client: entry.client })),\n );\n\n const unique: Array<{\n client: KontextClient;\n sourceId?: \"gateway\" | string;\n }> = [];\n const seen = new Set<KontextClient>();\n for (const entry of ordered) {\n if (seen.has(entry.client)) continue;\n seen.add(entry.client);\n unique.push(entry);\n }\n\n let handledBy:\n | {\n client: KontextClient;\n sourceId?: \"gateway\" | string;\n }\n | undefined;\n let lastError: unknown = undefined;\n\n for (const entry of unique) {\n try {\n await entry.client.auth.handleCallback(url);\n handledBy = entry;\n break;\n } catch (err) {\n lastError = err;\n }\n }\n\n if (handledBy) {\n for (let idx = authSourceQueue.length - 1; idx >= 0; idx -= 1) {\n const sourceId = authSourceQueue[idx]!;\n const sourceClient =\n sourceId === \"gateway\"\n ? gatewayClient\n : internalClientRegistry.get(sourceId)?.client;\n if (sourceClient === handledBy.client) {\n authSourceQueue.splice(idx, 1);\n }\n }\n }\n\n if (!handledBy && lastError) {\n throw toKontextError(lastError, {\n backendId: gatewayBackendId(),\n source: \"gateway\",\n operation: \"auth.handleCallback\",\n });\n }\n\n try {\n await ensureConnected();\n } catch (err) {\n stateController.emitError(\n toKontextError(err, {\n backendId: gatewayBackendId(),\n source: \"gateway\",\n operation: \"post_callback_connect\",\n }),\n );\n }\n },\n\n isCallback(url: string | URL): boolean {\n if (gatewayClient.auth.isCallback(url)) return true;\n for (const entry of internalClientRegistry.values()) {\n if (entry.client.auth.isCallback(url)) return true;\n }\n return false;\n },\n\n get isAuthenticated(): boolean {\n return (\n stateController.state === \"ready\" ||\n gatewayClient.auth.isAuthenticated\n );\n },\n },\n\n integrations: {\n async list(): Promise<IntegrationInfo[]> {\n await ensureConnected();\n const discovered = await refreshIntegrationInventory(true);\n\n let gatewayStatuses: IntegrationInfo[] = [];\n try {\n gatewayStatuses = await gatewayClient.integrations.list();\n } catch (err) {\n stateController.emitError(\n toKontextError(err, {\n backendId: gatewayBackendId(),\n source: \"gateway\",\n operation: \"integrations.list\",\n }),\n );\n }\n const gatewayById = new Map(gatewayStatuses.map((i) => [i.id, i]));\n\n const needsInternalConnectLink = discovered.some(\n (i) =>\n i.category === \"internal_mcp_credentials\" &&\n !i.connection?.connected,\n );\n\n let sharedConnectUrl: string | undefined;\n if (needsInternalConnectLink) {\n try {\n sharedConnectUrl = (await gatewayClient.getConnectPageUrl())\n .connectUrl;\n } catch {\n sharedConnectUrl = undefined;\n }\n }\n\n return discovered.map((integration) => {\n const gatewayStatus = gatewayById.get(integration.id);\n const connected =\n gatewayStatus?.connected ??\n integration.connection?.connected ??\n false;\n const connectUrl =\n gatewayStatus?.connectUrl ??\n (!connected && integration.category === \"internal_mcp_credentials\"\n ? sharedConnectUrl\n : undefined);\n const reason =\n gatewayStatus?.reason ??\n (!connected && integration.category === \"internal_mcp_credentials\"\n ? \"credentials_required\"\n : undefined);\n\n return {\n id: integration.id,\n name: integration.name,\n connected,\n connectUrl,\n reason,\n };\n });\n },\n },\n\n tools: {\n async list(options?: { limit?: number }): Promise<KontextTool[]> {\n await ensureConnected();\n let inventory = await buildToolInventory(options);\n\n const missingInternal = getInternalIntegrationsMissingTools();\n if (missingInternal.length > 0) {\n const refreshed = await refreshIntegrationInventory(true);\n inventory = await buildToolInventory({\n ...options,\n runtimeIntegrations: refreshed,\n });\n }\n emitRouteConflicts(inventory.conflicts);\n\n const unresolvedInternal = getInternalIntegrationsMissingTools();\n if (\n stateController.state === \"needs_auth\" &&\n gatewayClient.state === \"ready\" &&\n unresolvedInternal.length === 0\n ) {\n stateController.setState(\"ready\");\n }\n\n return inventory.tools;\n },\n\n async execute(\n toolId: string,\n args?: Record<string, unknown>,\n ): Promise<ToolResult> {\n await ensureConnected();\n\n const route = await routeForExecution(toolId);\n\n try {\n if (route.source === \"gateway\") {\n return await gatewayClient.tools.execute(route.backendToolId, args);\n }\n\n const integrationId = route.integrationId;\n if (!integrationId) {\n throw new KontextError(\n `Route for tool \"${toolId}\" is missing integration metadata.`,\n \"kontext_tool_not_found\",\n { meta: { toolId, route } },\n );\n }\n\n let entry = internalClientRegistry.get(integrationId);\n if (!entry) {\n await refreshIntegrationInventory(true);\n entry = internalClientRegistry.get(integrationId);\n }\n if (!entry) {\n throw new KontextError(\n `Internal integration \"${integrationId}\" is no longer attached.`,\n \"kontext_tool_not_found\",\n { meta: { integrationId } },\n );\n }\n\n await ensureInternalResourceToken(entry.integration);\n try {\n const executeInternal = async () =>\n await withTransientRetry(\n async () =>\n await runManagedInternalOp(integrationId, () =>\n entry.client.tools.execute(route.backendToolId, args),\n ),\n );\n return await executeInternal();\n } catch (innerErr) {\n const innerTranslated = toKontextError(innerErr, {\n backendId: route.backendId,\n source: route.source,\n integrationId: route.integrationId,\n operation: \"tools.execute\",\n toolId,\n });\n throw innerTranslated;\n }\n } catch (err) {\n const translated = toKontextError(err, {\n backendId: route.backendId,\n source: route.source,\n integrationId: route.integrationId,\n operation: \"tools.execute\",\n toolId,\n });\n if (isAuthRecoveryRequired(translated)) {\n stateController.setState(\"needs_auth\");\n }\n stateController.emitError(translated);\n throw translated;\n }\n },\n },\n\n on(\n event: \"stateChange\" | \"error\",\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n handler: (...args: any[]) => void,\n ): () => void {\n if (event === \"stateChange\") {\n return stateController.on(\"stateChange\", handler);\n }\n return stateController.on(\"error\", handler);\n },\n\n get mcp() {\n return gatewayClient.mcp;\n },\n };\n\n // Preserve lifecycle subscriptions.\n void gatewayStateUnsubscribe;\n void gatewayErrorUnsubscribe;\n\n return orchestrator;\n}\n","/**\n * KontextClient — protocol-agnostic facade over KontextMcp.\n *\n * Hides all MCP internals (SEARCH_TOOLS, EXECUTE_TOOL, -32042) behind a\n * clean, typed API. Advanced users can access the underlying KontextMcp\n * via `client.mcp`.\n *\n * @example\n * ```typescript\n * import { createKontextClient } from '@kontext-dev/js-sdk';\n *\n * const client = createKontextClient({\n * clientId: 'your-client-id',\n * redirectUri: 'http://localhost:3000/callback',\n * onAuthRequired: (url) => open(url.toString()),\n * });\n *\n * await client.connect();\n * const tools = await client.tools.list();\n * const result = await client.tools.execute('github:repos', { query: 'mcp' });\n * ```\n *\n * @packageDocumentation\n */\n\nimport { KontextMcp } from \"../mcp/client.js\";\nimport type { KontextStorage } from \"../storage/types.js\";\nimport { parseIntegrationStatus } from \"./tool-utils.js\";\nimport { createKontextOrchestrator } from \"./orchestrator/index.js\";\nimport type { ElicitationEntry } from \"../errors.js\";\nimport {\n AuthorizationRequiredError,\n IntegrationConnectionRequiredError,\n NetworkError,\n KontextError,\n ConfigError,\n isKontextError,\n isNetworkError,\n isUnauthorizedError,\n} from \"../errors.js\";\n\n// ============================================================================\n// Public types\n// ============================================================================\n\nexport type ClientState =\n | \"idle\"\n | \"connecting\"\n | \"ready\"\n | \"needs_auth\"\n | \"failed\";\n\nexport interface KontextClientConfig {\n clientId: string;\n redirectUri: 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 serverUrl?: string;\n storage?: KontextStorage;\n sessionKey?: string;\n\n onAuthRequired: (\n url: URL,\n ) => string | URL | void | Promise<string | URL | void>;\n onIntegrationRequired?: (\n url: string,\n info: { id: string; name?: string },\n ) => void | Promise<void>;\n onStateChange?: (state: ClientState) => void;\n}\n\nexport interface KontextTool {\n id: string;\n name: string;\n description?: string;\n inputSchema?: object;\n server?: { id: string; name?: string };\n}\n\nexport interface IntegrationInfo {\n id: string;\n name: string;\n connected: boolean;\n connectUrl?: string;\n reason?: string;\n}\n\nexport interface ToolResult {\n content: string;\n raw: unknown;\n}\n\nexport interface ConnectSessionResult {\n connectUrl: string;\n sessionId: string;\n expiresAt: string;\n}\n\nexport interface KontextClient {\n readonly state: ClientState;\n\n connect(): Promise<void>;\n disconnect(): Promise<void>;\n getConnectPageUrl(): Promise<ConnectSessionResult>;\n\n readonly auth: {\n signIn(): Promise<void>;\n signOut(): Promise<void>;\n handleCallback(url: string | URL): Promise<void>;\n isCallback(url: string | URL): boolean;\n readonly isAuthenticated: boolean;\n };\n\n readonly integrations: {\n list(): Promise<IntegrationInfo[]>;\n };\n\n readonly tools: {\n list(options?: { limit?: number }): Promise<KontextTool[]>;\n execute(\n toolId: string,\n args?: Record<string, unknown>,\n ): Promise<ToolResult>;\n };\n\n on(event: \"stateChange\", handler: (state: ClientState) => void): () => void;\n on(event: \"error\", handler: (error: KontextError) => void): () => void;\n\n /**\n * Advanced escape hatch to the raw MCP client.\n *\n * Note: In hybrid/orchestrator mode (`createKontextClient` called without\n * `url`), this is the gateway MCP client only. Tools from direct internal\n * integrations are exposed through `client.tools`, not through this property.\n */\n readonly mcp: KontextMcp;\n}\n\n// ============================================================================\n// Internal helpers — meta-tool detection & gateway parsing\n// ============================================================================\n\nconst META_TOOL_NAMES = new Set([\n \"SEARCH_TOOLS\",\n \"EXECUTE_TOOL\",\n \"REQUEST_CAPABILITY\",\n]);\n\nfunction hasMetaTools(tools: Array<{ name: string }>): boolean {\n let hasSearch = false;\n let hasExecute = false;\n for (const tool of tools) {\n if (tool.name === \"SEARCH_TOOLS\") hasSearch = true;\n if (tool.name === \"EXECUTE_TOOL\") hasExecute = true;\n }\n return hasSearch && hasExecute;\n}\n\ntype GatewayToolSummary = {\n id: string;\n name: string;\n description?: string;\n inputSchema?: unknown;\n server?: { id?: string; name?: string; url?: string };\n};\n\ntype GatewayToolError = {\n serverId: string;\n reason: string;\n serverName?: string;\n};\n\ntype McpContentItem = {\n type?: string;\n text?: string;\n resource?: { mimeType?: string; text?: string };\n};\n\nfunction extractJsonResourceText(result: unknown): string | null {\n if (!result || typeof result !== \"object\") return null;\n const content = (result as { content?: McpContentItem[] }).content;\n if (!Array.isArray(content)) return null;\n for (const item of content) {\n if (\n item.type === \"resource\" &&\n item.resource?.mimeType === \"application/json\" &&\n item.resource.text\n ) {\n return item.resource.text;\n }\n }\n return null;\n}\n\nfunction extractTextContent(result: unknown): string {\n if (!result || typeof result !== \"object\") return String(result ?? \"\");\n const r = result as { content?: McpContentItem[] };\n if (r.content && Array.isArray(r.content)) {\n const texts = r.content\n .filter((c) => c.type === \"text\" && c.text)\n .map((c) => c.text!);\n if (texts.length > 0) return texts.join(\"\\n\");\n\n // Meta-tool EXECUTE_TOOL responses are wrapped as resource JSON payloads.\n const resourceTexts = r.content\n .filter((c) => c.type === \"resource\" && c.resource?.text)\n .map((c) => c.resource!.text!);\n if (resourceTexts.length > 0) {\n return resourceTexts\n .map((text) => {\n try {\n return extractTextContent(JSON.parse(text));\n } catch {\n return text;\n }\n })\n .join(\"\\n\");\n }\n\n return JSON.stringify(r.content);\n }\n return JSON.stringify(result);\n}\n\n// ============================================================================\n// Error translation\n// ============================================================================\n\n/**\n * Translate external errors into KontextError instances.\n * Uses structural checks (numeric codes, status codes, system error codes)\n * rather than fragile string matching.\n */\nfunction translateError(err: unknown): KontextError {\n if (isKontextError(err)) return err as KontextError;\n\n if (!(err instanceof Error)) {\n return new KontextError(String(err), \"kontext_unknown_error\");\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const props: Record<string, any> = err;\n\n // 1. MCP protocol -32042 (URL elicitation required) — check numeric code\n if (props.code === -32042) {\n const elicitations = (props.elicitations ?? props.data?.elicitations) as\n | ElicitationEntry[]\n | undefined;\n const elicitation = elicitations?.[0];\n return new IntegrationConnectionRequiredError(\n elicitation?.integrationId ?? \"unknown\",\n {\n integrationName: elicitation?.integrationName,\n connectUrl: elicitation?.url,\n message: elicitation?.message,\n cause: err,\n },\n );\n }\n\n // 2. HTTP status on the error (from MCP SDK or fetch wrappers)\n const statusCode = (props.statusCode ?? props.status) as number | undefined;\n if (typeof statusCode === \"number\" && statusCode >= 400) {\n if (statusCode === 401) {\n return new AuthorizationRequiredError(err.message, { cause: err });\n }\n return new KontextError(err.message, \"kontext_server_error\", {\n statusCode,\n cause: err,\n });\n }\n\n // 3. Auth errors — structural check\n if (isUnauthorizedError(err)) {\n return new AuthorizationRequiredError(err.message, { cause: err });\n }\n\n // 4. Network errors — structural check (system error codes, not string matching)\n if (isNetworkError(err)) {\n return new NetworkError(err.message, { cause: err });\n }\n\n // 5. Fallback\n return new KontextError(err.message, \"kontext_unknown_error\", {\n cause: err,\n });\n}\n\n// ============================================================================\n// Factory\n// ============================================================================\n\nexport function createSingleEndpointKontextClient(\n config: KontextClientConfig,\n): KontextClient {\n if (!config.clientId) {\n throw new ConfigError(\n \"clientId is required. Pass it in KontextClientConfig or set KONTEXT_CLIENT_ID.\",\n \"kontext_config_missing_client_id\",\n );\n }\n if (!config.redirectUri) {\n throw new ConfigError(\n \"redirectUri is required. Set it to the URL where OAuth should redirect after authorization.\",\n \"kontext_config_missing_redirect_uri\",\n );\n }\n if (!config.onAuthRequired) {\n throw new ConfigError(\n \"onAuthRequired callback is required. Provide a function that opens the OAuth URL.\",\n \"kontext_config_missing_auth_handler\",\n );\n }\n\n let _state: ClientState = \"idle\";\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const _listeners = new Map<string, Set<(...args: any[]) => void>>();\n let _metaToolMode: boolean | null = null;\n\n // Build KontextMcp config — route elicitation to onIntegrationRequired\n const mcp = new KontextMcp({\n clientId: config.clientId,\n url: config.url,\n server: config.serverUrl,\n redirectUri: config.redirectUri,\n storage: config.storage,\n sessionKey: config.sessionKey,\n onAuthRequired: config.onAuthRequired,\n // Route MCP elicitation to the high-level callback.\n // KontextMcp calls this then re-throws; client.tools.execute() catches\n // the re-thrown error and handles translation.\n onElicitationUrl: config.onIntegrationRequired\n ? (entry) => {\n config.onIntegrationRequired!(entry.url, {\n id: entry.integrationId ?? \"unknown\",\n name: entry.integrationName ?? entry.message,\n });\n }\n : undefined,\n });\n\n // -- State machine helpers --\n\n function setState(newState: ClientState) {\n if (_state === newState) return;\n _state = newState;\n try {\n config.onStateChange?.(newState);\n } catch {\n // Don't let listener errors break state transitions\n }\n const handlers = _listeners.get(\"stateChange\");\n if (handlers) {\n for (const handler of handlers) {\n try {\n handler(newState);\n } catch {\n // Don't let listener errors break state transitions\n }\n }\n }\n }\n\n function emitError(error: KontextError) {\n const handlers = _listeners.get(\"error\");\n if (handlers) {\n for (const handler of handlers) {\n try {\n handler(error);\n } catch {\n // Don't let listener errors mask the original error\n }\n }\n }\n }\n\n // -- Gateway tool helpers --\n\n async function fetchGatewayTools(limit = 100): Promise<{\n tools: GatewayToolSummary[];\n errors: GatewayToolError[];\n elicitations?: Array<{\n url: string;\n message?: string;\n integrationId?: string;\n integrationName?: string;\n }>;\n }> {\n const result = await mcp.callTool(\"SEARCH_TOOLS\", { limit });\n const jsonText = extractJsonResourceText(result);\n if (!jsonText) {\n throw new KontextError(\n \"SEARCH_TOOLS did not return JSON resource content. The server may not support the gateway protocol.\",\n \"kontext_tool_response_empty\",\n );\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(jsonText);\n } catch (e) {\n throw new KontextError(\n `SEARCH_TOOLS returned invalid JSON: ${e instanceof Error ? e.message : String(e)}`,\n \"kontext_tool_response_invalid_json\",\n );\n }\n if (Array.isArray(parsed)) {\n return { tools: parsed as GatewayToolSummary[], errors: [] };\n }\n if (parsed && typeof parsed === \"object\") {\n const obj = parsed as Record<string, unknown>;\n return {\n tools: Array.isArray(obj.items) ? obj.items : [],\n errors: Array.isArray(obj.errors) ? obj.errors : [],\n elicitations: Array.isArray(obj.elicitations)\n ? obj.elicitations\n : undefined,\n };\n }\n throw new KontextError(\n \"SEARCH_TOOLS response was not a JSON array or object. Check the server version.\",\n \"kontext_tool_response_unexpected\",\n );\n }\n\n function toKontextTool(tool: GatewayToolSummary): KontextTool {\n return {\n id: tool.id,\n name: tool.name,\n description: tool.description,\n inputSchema: tool.inputSchema as object | undefined,\n server: tool.server\n ? { id: tool.server.id ?? \"\", name: tool.server.name }\n : undefined,\n };\n }\n\n async function ensureConnected(): Promise<void> {\n if (_state === \"ready\" && mcp.isConnected) return;\n setState(\"connecting\");\n try {\n // listTools() triggers lazy connection inside KontextMcp\n const mcpTools = await mcp.listTools();\n _metaToolMode = hasMetaTools(mcpTools);\n setState(\"ready\");\n } catch (err) {\n const translated = translateError(err);\n if (translated instanceof AuthorizationRequiredError) {\n setState(\"needs_auth\");\n } else {\n setState(\"failed\");\n }\n emitError(translated);\n throw translated;\n }\n }\n\n // -- Public interface --\n\n const client: KontextClient = {\n get state() {\n return _state;\n },\n\n async connect() {\n await ensureConnected();\n },\n\n async disconnect() {\n await mcp.disconnect();\n _metaToolMode = null;\n setState(\"idle\");\n },\n\n async getConnectPageUrl(): Promise<ConnectSessionResult> {\n await ensureConnected();\n try {\n return await mcp.createConnectSession();\n } catch (err) {\n const translated = translateError(err);\n if (translated instanceof AuthorizationRequiredError) {\n setState(\"needs_auth\");\n }\n throw translated;\n }\n },\n\n auth: {\n async signIn() {\n await ensureConnected();\n },\n\n async signOut() {\n await mcp.clearAuth();\n _metaToolMode = null;\n setState(\"idle\");\n },\n\n async handleCallback(url: string | URL) {\n await mcp.handleCallback(url);\n try {\n await ensureConnected();\n } catch (err) {\n // Connection may not succeed yet — emit error but don't throw\n // since the callback itself was handled successfully\n emitError(translateError(err));\n }\n },\n\n isCallback(url: string | URL): boolean {\n return mcp.isCallback(url);\n },\n\n get isAuthenticated(): boolean {\n return _state === \"ready\" || mcp.isConnected;\n },\n },\n\n integrations: {\n async list(): Promise<IntegrationInfo[]> {\n await ensureConnected();\n try {\n const { tools, errors, elicitations } = await fetchGatewayTools();\n\n const statuses = parseIntegrationStatus(tools, errors, elicitations);\n\n // Enrich with reason from errors\n const errorMap = new Map(errors.map((e) => [e.serverId, e.reason]));\n return statuses.map((s) => {\n const reason = errorMap.get(s.id);\n return reason ? { ...s, reason } : s;\n });\n } catch (err) {\n const translated = translateError(err);\n if (translated instanceof AuthorizationRequiredError) {\n setState(\"needs_auth\");\n }\n throw translated;\n }\n },\n },\n\n tools: {\n async list(options?: { limit?: number }): Promise<KontextTool[]> {\n await ensureConnected();\n try {\n const mcpTools = await mcp.listTools();\n const nonMetaTools = mcpTools.filter(\n (t) => !META_TOOL_NAMES.has(t.name),\n );\n\n if (nonMetaTools.length > 0 || !hasMetaTools(mcpTools)) {\n _metaToolMode = false;\n return nonMetaTools.map((t) => ({\n id: t.name,\n name: t.name,\n description: t.description,\n inputSchema: t.inputSchema as object | undefined,\n }));\n }\n\n _metaToolMode = true;\n const { tools, elicitations } = await fetchGatewayTools(\n options?.limit,\n );\n\n // If the server returned embedded elicitations (partial result with\n // some servers needing OAuth), invoke the onIntegrationRequired callback\n // so the user can connect the missing integrations.\n if (elicitations?.length && config.onIntegrationRequired) {\n for (const e of elicitations) {\n if (e.url) {\n config.onIntegrationRequired(e.url, {\n id: e.integrationId ?? \"\",\n name: e.integrationName ?? e.message,\n });\n }\n }\n }\n\n return tools.map(toKontextTool);\n } catch (err) {\n const translated = translateError(err);\n if (translated instanceof AuthorizationRequiredError) {\n setState(\"needs_auth\");\n }\n throw translated;\n }\n },\n\n async execute(\n toolId: string,\n args?: Record<string, unknown>,\n ): Promise<ToolResult> {\n await ensureConnected();\n\n // Determine meta-tool mode if not yet known\n if (_metaToolMode === null) {\n const mcpTools = await mcp.listTools();\n _metaToolMode = hasMetaTools(mcpTools);\n }\n\n try {\n const result = _metaToolMode\n ? await mcp.callTool(\"EXECUTE_TOOL\", {\n tool_id: toolId,\n tool_arguments: args ?? {},\n })\n : await mcp.callTool(toolId, args);\n\n return { content: extractTextContent(result), raw: result };\n } catch (err) {\n const translated = translateError(err);\n if (translated instanceof AuthorizationRequiredError) {\n setState(\"needs_auth\");\n }\n throw translated;\n }\n },\n },\n\n on(\n event: \"stateChange\" | \"error\",\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n handler: (...args: any[]) => void,\n ): () => void {\n if (!_listeners.has(event)) {\n _listeners.set(event, new Set());\n }\n _listeners.get(event)!.add(handler);\n return () => {\n _listeners.get(event)?.delete(handler);\n };\n },\n\n get mcp() {\n return mcp;\n },\n };\n\n return client;\n}\n\n/**\n * Primary SDK client entrypoint.\n *\n * - `config.url` set: single-endpoint mode.\n * - `config.url` omitted: hybrid orchestrated mode.\n */\nexport function createKontextClient(\n config: KontextClientConfig & { url: string },\n): KontextClient;\nexport function createKontextClient(\n config: Omit<KontextClientConfig, \"url\"> & { url?: undefined },\n): KontextClient;\nexport function createKontextClient(\n config: KontextClientConfig,\n): KontextClient {\n if (config.url !== undefined) {\n if (typeof config.url !== \"string\" || config.url.trim().length === 0) {\n throw new ConfigError(\n \"url must be a non-empty string. Omit url for hybrid mode, or provide a full MCP endpoint URL.\",\n \"kontext_config_invalid_url\",\n );\n }\n return createSingleEndpointKontextClient(config);\n }\n\n return createKontextOrchestrator(config);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/storage/memory.ts","../../src/storage/types.ts","../../src/errors.ts","../../src/oauth/provider.ts","../../src/mcp/client.ts","../../src/client/tool-utils.ts","../../src/client/orchestrator/internal/backends.ts","../../src/client/orchestrator/internal/routes.ts","../../src/client/orchestrator/internal/inventory.ts","../../src/client/orchestrator/internal/policy.ts","../../src/client/orchestrator/internal/state.ts","../../src/client/orchestrator/token-manager.ts","../../src/client/orchestrator/internal-client-registry.ts","../../src/client/orchestrator/index.ts","../../src/client/index.ts"],"names":[],"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,MA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sBAAsB,0BAAA,EAA4B;AACpD,YAAA,QAAA,CAAS,YAAY,CAAA;AAAA,UACvB;AACA,UAAA,MAAM,UAAA;AAAA,QACR;AAAA,MACF;AAAA,KACF;AAAA,IAEA,EAAA,CACE,OAEA,OAAA,EACY;AACZ,MAAA,IAAI,CAAC,UAAA,CAAW,GAAA,CAAI,KAAK,CAAA,EAAG;AAC1B,QAAA,UAAA,CAAW,GAAA,CAAI,KAAA,kBAAO,IAAI,GAAA,EAAK,CAAA;AAAA,MACjC;AACA,MAAA,UAAA,CAAW,GAAA,CAAI,KAAK,CAAA,CAAG,GAAA,CAAI,OAAO,CAAA;AAClC,MAAA,OAAO,MAAM;AACX,QAAA,UAAA,CAAW,GAAA,CAAI,KAAK,CAAA,EAAG,MAAA,CAAO,OAAO,CAAA;AAAA,MACvC,CAAA;AAAA,IACF,CAAA;AAAA,IAEA,IAAI,GAAA,GAAM;AACR,MAAA,OAAO,GAAA;AAAA,IACT;AAAA,GACF;AAEA,EAAA,OAAO,MAAA;AACT;AAcO,SAAS,oBACd,MAAA,EACe;AACf,EAAA,IAAI,MAAA,CAAO,QAAQ,MAAA,EAAW;AAC5B,IAAA,IAAI,OAAO,OAAO,GAAA,KAAQ,QAAA,IAAY,OAAO,GAAA,CAAI,IAAA,EAAK,CAAE,MAAA,KAAW,CAAA,EAAG;AACpE,MAAA,MAAM,IAAI,WAAA;AAAA,QACR,+FAAA;AAAA,QACA;AAAA,OACF;AAAA,IACF;AACA,IAAA,OAAO,kCAAkC,MAAM,CAAA;AAAA,EACjD;AAEA,EAAA,OAAO,0BAA0B,MAAM,CAAA;AACzC","file":"index.js","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\nimport { ErrorCode } from \"@modelcontextprotocol/sdk/types.js\";\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 // Browser fetch() failures: TypeError with known messages, no system error code\n if (err.name === \"TypeError\") {\n const msg = err.message.toLowerCase();\n if (\n msg === \"failed to fetch\" ||\n msg === \"load failed\" ||\n msg.includes(\"networkerror\")\n ) {\n return true;\n }\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 // StreamableHTTPError stores status as `.code`\n if (props.code === 401) return true;\n\n // MCP SDK UnauthorizedError extends Error without setting `.name`,\n // so `.name` is \"Error\". Use constructor name as fallback.\n if (err.name === \"UnauthorizedError\") return true;\n if (err.constructor?.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// ============================================================================\n// MCP error translation\n// ============================================================================\n\nconst MCP_CODE_MAP: Record<number, { code: string; statusCode?: number }> = {\n [ErrorCode.ParseError]: { code: \"kontext_mcp_parse_error\" },\n [ErrorCode.InvalidRequest]: { code: \"kontext_mcp_invalid_request\" },\n [ErrorCode.MethodNotFound]: { code: \"kontext_mcp_method_not_found\" },\n [ErrorCode.InvalidParams]: { code: \"kontext_mcp_invalid_params\" },\n [ErrorCode.InternalError]: {\n code: \"kontext_mcp_internal_error\",\n statusCode: 500,\n },\n [ErrorCode.RequestTimeout]: {\n code: \"kontext_mcp_session_expired\",\n statusCode: 401,\n },\n [ErrorCode.ConnectionClosed]: { code: \"kontext_mcp_session_error\" },\n};\n\n/**\n * Translate external errors into KontextError instances.\n * Uses structural checks (numeric codes, status codes, system error codes)\n * rather than fragile string matching.\n */\nexport function translateError(err: unknown): KontextError {\n if (isKontextError(err)) return err as KontextError;\n\n if (!(err instanceof Error)) {\n return new KontextError(String(err), \"kontext_unknown_error\");\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const props: Record<string, any> = err;\n\n // 1. MCP protocol -32042 (URL elicitation required) — check numeric code\n if (props.code === ErrorCode.UrlElicitationRequired) {\n const elicitations = (props.elicitations ?? props.data?.elicitations) as\n | ElicitationEntry[]\n | undefined;\n const elicitation = elicitations?.[0];\n return new IntegrationConnectionRequiredError(\n elicitation?.integrationId ?? \"unknown\",\n {\n integrationName: elicitation?.integrationName,\n connectUrl: elicitation?.url,\n message: elicitation?.message,\n cause: err,\n },\n );\n }\n\n // 2. MCP JSON-RPC errors (standard and server-defined ranges)\n if (typeof props.code === \"number\" && props.code < 0) {\n const entry = MCP_CODE_MAP[props.code];\n if (entry) {\n return new KontextError(err.message, entry.code, {\n statusCode: entry.statusCode,\n cause: err,\n });\n }\n return new KontextError(err.message, \"kontext_mcp_error\", {\n cause: err,\n meta: { mcpCode: props.code },\n });\n }\n\n // 3. HTTP status on the error (from MCP SDK or fetch wrappers)\n // StreamableHTTPError stores HTTP status as `.code` (not `.statusCode`/`.status`),\n // so check `.code` as well when it's in the HTTP error range (400–599).\n const statusCode = (props.statusCode ??\n props.status ??\n (typeof props.code === \"number\" && props.code >= 400 && props.code < 600\n ? props.code\n : undefined)) as number | undefined;\n if (typeof statusCode === \"number\" && statusCode >= 400) {\n if (statusCode === 401) {\n return new AuthorizationRequiredError(err.message, { cause: err });\n }\n return new KontextError(err.message, \"kontext_server_error\", {\n statusCode,\n cause: err,\n });\n }\n\n // 4. Auth errors — structural check\n if (isUnauthorizedError(err)) {\n return new AuthorizationRequiredError(err.message, { cause: err });\n }\n\n // 5. Network errors — structural check (system error codes, not string matching)\n if (isNetworkError(err)) {\n return new NetworkError(err.message, { cause: err });\n }\n\n // 6. Fallback\n return new KontextError(err.message, \"kontext_unknown_error\", {\n cause: err,\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 lastVerifiedAt?: string;\n lastVerifiedStatus?: string;\n verificationMessage?: 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","/**\n * Shared utilities for Kontext tool handling.\n * Used by both KontextClient (core) and withKontext (Cloudflare adapter).\n */\n\nimport {\n ConfigError,\n IntegrationConnectionRequiredError,\n type ElicitationEntry,\n} from \"../errors.js\";\n\n// Re-export for consumers that import this type from tool-utils.\nexport type { ElicitationEntry } from \"../errors.js\";\n\n// ============================================================================\n// Shared types\n// ============================================================================\n\nexport interface IntegrationStatus {\n readonly id: string;\n readonly name: string;\n readonly connected: boolean;\n readonly connectUrl?: string;\n}\n\n// ============================================================================\n// System prompt\n// ============================================================================\n\n/**\n * Build an LLM system prompt based on available tool names and integration status.\n * Detects `*_SEARCH_TOOLS` / `*_EXECUTE_TOOL` suffixed names from the\n * Cloudflare Agents MCP proxy and generates appropriate guidance.\n */\nexport function buildKontextSystemPrompt(\n toolNames: readonly string[],\n integrations: readonly IntegrationStatus[],\n): string {\n if (toolNames.length === 0) return \"\";\n\n const searchTool = toolNames.find(\n (n) => n.endsWith(\"_SEARCH_TOOLS\") || n === \"SEARCH_TOOLS\",\n );\n const executeTool = toolNames.find(\n (n) => n.endsWith(\"_EXECUTE_TOOL\") || n === \"EXECUTE_TOOL\",\n );\n const requestCapabilityTool = toolNames.find(\n (n) => n.endsWith(\"_REQUEST_CAPABILITY\") || n === \"REQUEST_CAPABILITY\",\n );\n\n let prompt =\n \"You are a helpful assistant with access to various tools and integrations through Kontext.\\n\" +\n \"You can help users with tasks across their connected services (GitHub, Linear, Slack, etc.).\\n\" +\n \"When a user asks about their services, use the available MCP tools to help them.\\n\" +\n \"The user has already authenticated — tools run as the user with their permissions, including access to private repositories and org resources.\\n\" +\n \"If a Kontext tool can satisfy an integration-related request, use the Kontext tool and do not use shell or CLI commands for that request.\\n\" +\n \"Use shell or CLI only when no relevant Kontext tool exists or when the user explicitly requests local shell actions.\";\n\n if (searchTool && executeTool) {\n prompt +=\n `\\n\\nYou have access to external integrations through Kontext MCP tools:\\n` +\n `- Call \\`${searchTool}\\` first to discover what tools/integrations are available.\\n` +\n `- Then call \\`${executeTool}\\` with the tool_id and arguments to run a specific tool.\\n` +\n `- When the user asks about \"my repos\", \"my issues\", etc., use the appropriate tool to look up their data directly. Do not ask for their username — the tools already know who they are.\\n` +\n `Always start by searching for tools when the user asks about their connected services.`;\n }\n\n // Append integration status section when there are integrations to report\n if (integrations.length > 0) {\n const connected = integrations.filter((i) => i.connected);\n const disconnected = integrations.filter((i) => !i.connected);\n\n if (disconnected.length > 0) {\n prompt += \"\\n\\n## Integration Status\";\n\n if (connected.length > 0) {\n prompt += `\\n\\nYou already have access to: ${connected.map((i) => i.name).join(\", \")}`;\n }\n\n prompt += `\\n\\nThe following services require user authorization: ${disconnected.map((i) => i.name).join(\", \")}`;\n\n if (requestCapabilityTool) {\n prompt +=\n `\\n\\n**IMPORTANT:** When the user requests an action that requires one of these services:` +\n `\\n1. Call the \\`${requestCapabilityTool}\\` tool` +\n `\\n2. The tool returns a fresh integrations management link` +\n `\\n3. Include the link in your response so the user can connect or manage integrations` +\n `\\n4. Always call the tool for a fresh link and never reuse a previously returned URL`;\n } else {\n prompt +=\n \"\\n\\nWhen the user asks about a disconnected integration, let them know it needs to be connected first. Do not attempt to use tools from disconnected integrations without informing the user.\";\n }\n } else if (requestCapabilityTool && connected.length > 0) {\n prompt +=\n \"\\n\\n## Integration Management\" +\n `\\n\\nIf the user asks to manage, reconnect, or verify integrations, call \\`${requestCapabilityTool}\\` to get a fresh integrations management link.`;\n }\n }\n\n return prompt;\n}\n\n// ============================================================================\n// Auth-aware toolset orchestrator\n// ============================================================================\n\nexport interface AuthAwareToolset {\n /** System prompt with integration status and REQUEST_CAPABILITY instructions. */\n readonly systemPrompt: string;\n /** REQUEST_CAPABILITY tool to inject, or null if all integrations are connected. */\n readonly requestCapabilityTool: {\n readonly name: string;\n readonly description: string;\n readonly parameters: Record<string, unknown>;\n readonly execute: () => Promise<string>;\n } | null;\n}\n\n/**\n * Enrich a tool set with auth awareness.\n *\n * Given tool names and integration status, produces:\n * - A system prompt that tells the LLM about connected/disconnected integrations\n * - A REQUEST_CAPABILITY tool (if needed) that returns a fresh management URL as text\n *\n * Both `ai/` and `cloudflare/` adapters use this as their core auth layer.\n */\nexport function enrichToolsWithAuthAwareness(\n toolNames: readonly string[],\n integrations: readonly IntegrationStatus[],\n options?: {\n prefix?: string;\n requireServerRequestCapability?: boolean;\n requestCapabilityProxy?: () => Promise<string>;\n },\n): AuthAwareToolset {\n const serverRequestCapability = toolNames.find(\n (name) =>\n name.endsWith(\"_REQUEST_CAPABILITY\") || name === \"REQUEST_CAPABILITY\",\n );\n\n if (options?.requireServerRequestCapability && !serverRequestCapability) {\n throw new ConfigError(\n \"REQUEST_CAPABILITY tool is required but not exposed by the MCP server. Deploy API and SDK in lockstep.\",\n \"kontext_config_missing_request_capability_tool\",\n );\n }\n\n let requestCapabilityTool: AuthAwareToolset[\"requestCapabilityTool\"] = null;\n let effectiveToolNames = [...toolNames];\n\n if (options?.requestCapabilityProxy) {\n const prefix =\n options.prefix ??\n toolNames\n .find((n) => n.endsWith(\"_SEARCH_TOOLS\"))\n ?.replace(/_SEARCH_TOOLS$/, \"\") ??\n \"kontext\";\n const toolName = `${prefix}_REQUEST_CAPABILITY`;\n const tool = buildRequestCapabilityTool(\n integrations,\n options.requestCapabilityProxy!,\n );\n requestCapabilityTool = { name: toolName, ...tool };\n effectiveToolNames = [...effectiveToolNames, toolName];\n }\n\n return {\n systemPrompt: buildKontextSystemPrompt(effectiveToolNames, integrations),\n requestCapabilityTool,\n };\n}\n\n// ============================================================================\n// Integration status parsing\n// ============================================================================\n\n/**\n * Parse integration status from gateway tool search results.\n * Extracts connected integrations from tools and disconnected from errors.\n */\nexport function parseIntegrationStatus(\n tools: ReadonlyArray<{ server?: { id?: string; name?: string } }>,\n errors: ReadonlyArray<{ serverId: string; serverName?: string }>,\n elicitations?: ReadonlyArray<{\n url: string;\n integrationId?: string;\n integrationName?: string;\n }>,\n): IntegrationStatus[] {\n const seen = new Set<string>();\n const result: IntegrationStatus[] = [];\n\n for (const t of tools) {\n const sid = t.server?.id;\n if (sid && !seen.has(sid)) {\n seen.add(sid);\n result.push({\n id: sid,\n name: t.server?.name ?? sid,\n connected: true,\n });\n }\n }\n\n for (const e of errors) {\n if (!seen.has(e.serverId)) {\n seen.add(e.serverId);\n const elicitation = elicitations?.find(\n (el) => el.integrationId === e.serverId,\n );\n result.push({\n id: e.serverId,\n name: e.serverName ?? e.serverId,\n connected: false,\n connectUrl: elicitation?.url,\n });\n }\n }\n\n return result;\n}\n\n// ============================================================================\n// Request capability tool\n// ============================================================================\n\n/**\n * Build a tool that lets the LLM request a fresh integrations management URL.\n * Returns the URL as text so the LLM can present it to the user.\n * No popups — the user clicks the link in the chat.\n */\nexport function buildRequestCapabilityTool(\n capabilities: readonly IntegrationStatus[],\n executeRequestCapability: () => Promise<string>,\n): {\n description: string;\n parameters: Record<string, unknown>;\n execute: () => Promise<string>;\n} {\n const connected = capabilities.filter((c) => c.connected);\n const disconnected = capabilities.filter((c) => !c.connected);\n const connectedList =\n connected.length > 0 ? connected.map((c) => c.name).join(\", \") : \"none\";\n const disconnectedList =\n disconnected.length > 0\n ? disconnected.map((c) => c.name).join(\", \")\n : \"none\";\n\n return {\n description:\n \"Request a fresh integrations management link from the Kontext server. \" +\n `Connected integrations: ${connectedList}. ` +\n `Disconnected integrations: ${disconnectedList}. ` +\n \"Always call this tool for a fresh link and never reuse an older link.\",\n parameters: {\n type: \"object\",\n properties: {},\n },\n execute: async (): Promise<string> => {\n return executeRequestCapability();\n },\n };\n}\n\n/**\n * Pre-flight integration status detection.\n * Calls SEARCH_TOOLS on raw (unwrapped) tools to detect connected/disconnected\n * integrations without triggering any popups or broadcasts.\n */\nexport async function preflightIntegrationStatus(\n tools: ToolSetLike,\n): Promise<IntegrationStatus[]> {\n const searchToolKey = Object.keys(tools).find((k) =>\n k.endsWith(\"_SEARCH_TOOLS\"),\n );\n if (!searchToolKey || !tools[searchToolKey]?.execute) return [];\n\n try {\n const result = await tools[searchToolKey].execute!({ limit: 100 });\n\n // Cloudflare getAITools() returns MCP CallToolResult objects, not strings.\n // Extract JSON text from either a plain string or a CallToolResult shape.\n let json: string | undefined;\n if (typeof result === \"string\") {\n json = result;\n } else if (result && typeof result === \"object\") {\n const content = (\n result as {\n content?: Array<{\n type: string;\n resource?: { text?: string };\n text?: string;\n }>;\n }\n ).content;\n const first = content?.[0];\n json = first?.resource?.text ?? first?.text;\n }\n\n if (typeof json === \"string\") {\n const parsed = JSON.parse(json);\n if (parsed && typeof parsed === \"object\") {\n return parseIntegrationStatus(\n Array.isArray(parsed.items) ? parsed.items : [],\n Array.isArray(parsed.errors) ? parsed.errors : [],\n Array.isArray(parsed.elicitations) ? parsed.elicitations : [],\n );\n }\n }\n } catch (err: unknown) {\n // All integrations disconnected: -32042 error contains elicitations\n const elicitations = extractElicitations(err);\n if (elicitations?.length) {\n return elicitations\n .filter(\n (e): e is ElicitationEntry & { integrationId: string } =>\n !!e.integrationId,\n )\n .map((e) => ({\n id: e.integrationId,\n name: e.integrationName ?? e.integrationId,\n connected: false,\n connectUrl: e.url,\n }));\n }\n }\n\n return [];\n}\n\n// ============================================================================\n// Tool wrapping\n// ============================================================================\n\n/** A tool with an optional async execute method */\nexport interface ToolLike {\n execute?: (...args: unknown[]) => Promise<unknown>;\n [key: string]: unknown;\n}\n\n/** Record of named tools */\nexport type ToolSetLike = Record<string, ToolLike>;\n\n/**\n * Extract elicitation entries from an error thrown by the MCP SDK.\n * Handles two shapes: direct code/data and nested cause.\n */\nexport function extractElicitations(\n err: unknown,\n): ElicitationEntry[] | undefined {\n const error = err as {\n code?: number;\n data?: { elicitations?: ElicitationEntry[] };\n cause?: {\n code?: number;\n data?: { elicitations?: ElicitationEntry[] };\n };\n };\n\n // Primary: structured McpError with code -32042\n if (error?.code === -32042 && error?.data?.elicitations?.length) {\n return error.data.elicitations;\n }\n\n // Nested cause (some SDK wrappers nest the original error)\n if (\n error?.cause?.code === -32042 &&\n error?.cause?.data?.elicitations?.length\n ) {\n return error.cause.data.elicitations;\n }\n\n return undefined;\n}\n\n/**\n * Wrap tools to catch MCP error code -32042 (URL elicitation required)\n * and convert to IntegrationConnectionRequiredError.\n */\nexport function wrapToolsWithElicitation<T extends ToolSetLike>(tools: T): T {\n return Object.fromEntries(\n Object.entries(tools).map(([name, tool]) => [\n name,\n {\n ...tool,\n execute: tool.execute\n ? async (...args: unknown[]) => {\n try {\n return await tool.execute!(...args);\n } catch (err: unknown) {\n const elicitations = extractElicitations(err);\n const elicitation = elicitations?.[0];\n if (elicitation?.url) {\n const integrationId = elicitation.integrationId ?? \"unknown\";\n throw new IntegrationConnectionRequiredError(integrationId, {\n integrationName: elicitation.integrationName,\n connectUrl: elicitation.url,\n message: elicitation.message,\n });\n }\n throw err;\n }\n }\n : undefined,\n },\n ]),\n ) as T;\n}\n","import type { KontextClient } from \"../../index.js\";\nimport type { RuntimeIntegrationRecord } from \"../../../mcp/client.js\";\n\nexport type BackendSource = \"gateway\" | \"internal\";\n\nexport interface RoutingBackend {\n backendId: string;\n source: BackendSource;\n client: KontextClient;\n integrationId?: string;\n integrationName?: string;\n}\n\nexport function gatewayBackendId(): \"gateway\" {\n return \"gateway\";\n}\n\nexport function internalBackendId(integrationId: string): string {\n return `internal:${integrationId}`;\n}\n\nexport function isInternalIntegration(\n integration: RuntimeIntegrationRecord,\n): boolean {\n return integration.category === \"internal_mcp_credentials\";\n}\n\nexport function sortInternalIntegrations(\n integrations: RuntimeIntegrationRecord[],\n): RuntimeIntegrationRecord[] {\n return integrations\n .filter(isInternalIntegration)\n .sort((a, b) => a.id.localeCompare(b.id));\n}\n\nexport function createGatewayBackend(client: KontextClient): RoutingBackend {\n return {\n backendId: gatewayBackendId(),\n source: \"gateway\",\n client,\n };\n}\n\nexport function createInternalBackend(input: {\n integration: RuntimeIntegrationRecord;\n client: KontextClient;\n}): RoutingBackend {\n return {\n backendId: internalBackendId(input.integration.id),\n source: \"internal\",\n client: input.client,\n integrationId: input.integration.id,\n integrationName: input.integration.name,\n };\n}\n","import type { KontextTool } from \"../../index.js\";\nimport type { BackendSource } from \"./backends.js\";\n\nexport interface ToolRouteRecord {\n toolId: string;\n backendId: string;\n source: BackendSource;\n backendToolId: string;\n integrationId?: string;\n}\n\nexport interface RouteInventoryCandidate {\n tool: KontextTool;\n route: ToolRouteRecord;\n}\n\nexport interface RouteConflictRecord {\n toolId: string;\n kept: ToolRouteRecord;\n dropped: ToolRouteRecord;\n}\n\nexport interface RouteInventorySnapshot {\n version: number;\n tools: KontextTool[];\n routes: Map<string, ToolRouteRecord>;\n conflicts: RouteConflictRecord[];\n}\n\nexport function emptyRouteInventorySnapshot(): RouteInventorySnapshot {\n return {\n version: 0,\n tools: [],\n routes: new Map(),\n conflicts: [],\n };\n}\n\nexport function buildRouteInventory(\n version: number,\n candidates: RouteInventoryCandidate[],\n options?: {\n onConflict?: (\n existing: ToolRouteRecord,\n incoming: ToolRouteRecord,\n ) => \"keep_existing\" | \"replace_existing\";\n },\n): RouteInventorySnapshot {\n const tools: KontextTool[] = [];\n const routes = new Map<string, ToolRouteRecord>();\n const conflicts: RouteConflictRecord[] = [];\n\n for (const candidate of candidates) {\n const toolId = candidate.route.toolId;\n if (!routes.has(toolId)) {\n routes.set(toolId, candidate.route);\n tools.push(candidate.tool);\n continue;\n }\n\n const existing = routes.get(toolId)!;\n const decision =\n options?.onConflict?.(existing, candidate.route) ?? \"keep_existing\";\n\n let kept = existing;\n let dropped = candidate.route;\n if (decision === \"replace_existing\") {\n const existingIdx = tools.findIndex((tool) => tool.id === toolId);\n if (existingIdx >= 0) {\n tools.splice(existingIdx, 1, candidate.tool);\n } else {\n tools.push(candidate.tool);\n }\n routes.set(toolId, candidate.route);\n kept = candidate.route;\n dropped = existing;\n }\n\n conflicts.push({\n toolId,\n kept,\n dropped,\n });\n }\n\n return {\n version,\n tools,\n routes,\n conflicts,\n };\n}\n","import {\n buildRouteInventory,\n emptyRouteInventorySnapshot,\n type RouteInventoryCandidate,\n type RouteInventorySnapshot,\n type ToolRouteRecord,\n} from \"./routes.js\";\n\nexport class RouteInventoryStore {\n private versionCounter = 0;\n private resetGeneration = 0;\n private buildRunCounter = 0;\n private latestCommittedBuildRun = 0;\n private snapshotState: RouteInventorySnapshot = emptyRouteInventorySnapshot();\n private pendingBuilds = new Map<string, Promise<RouteInventorySnapshot>>();\n\n get version(): number {\n return this.snapshotState.version;\n }\n\n get snapshot(): RouteInventorySnapshot {\n return this.snapshotState;\n }\n\n routeFor(toolId: string): ToolRouteRecord | undefined {\n return this.snapshotState.routes.get(toolId);\n }\n\n async build(\n buildCandidates: () => Promise<RouteInventoryCandidate[]>,\n options?: {\n key?: string;\n onConflict?: (\n existing: ToolRouteRecord,\n incoming: ToolRouteRecord,\n ) => \"keep_existing\" | \"replace_existing\";\n },\n ): Promise<RouteInventorySnapshot> {\n const key = options?.key ?? \"__default__\";\n const existingBuild = this.pendingBuilds.get(key);\n if (existingBuild) {\n return await existingBuild;\n }\n\n const buildGeneration = this.resetGeneration;\n const buildRun = ++this.buildRunCounter;\n const pendingPromise = (async () => {\n const candidates = await buildCandidates();\n if (this.resetGeneration !== buildGeneration) {\n return this.snapshotState;\n }\n if (buildRun >= this.latestCommittedBuildRun) {\n this.latestCommittedBuildRun = buildRun;\n this.versionCounter += 1;\n const snapshot = buildRouteInventory(this.versionCounter, candidates, {\n onConflict: options?.onConflict,\n });\n this.snapshotState = snapshot;\n return snapshot;\n }\n\n return buildRouteInventory(this.snapshotState.version, candidates, {\n onConflict: options?.onConflict,\n });\n })();\n this.pendingBuilds.set(key, pendingPromise);\n\n try {\n return await pendingPromise;\n } finally {\n if (this.pendingBuilds.get(key) === pendingPromise) {\n this.pendingBuilds.delete(key);\n }\n }\n }\n\n reset(): void {\n this.resetGeneration += 1;\n this.versionCounter = 0;\n this.latestCommittedBuildRun = this.buildRunCounter;\n this.snapshotState = emptyRouteInventorySnapshot();\n this.pendingBuilds.clear();\n }\n}\n","import { KontextError } from \"../../../errors.js\";\nimport type { ToolRouteRecord } from \"./routes.js\";\n\nexport interface RoutingPolicy {\n onRouteConflict(input: {\n toolId: string;\n existing: ToolRouteRecord;\n incoming: ToolRouteRecord;\n }): \"keep_existing\" | \"replace_existing\";\n}\n\nexport const defaultRoutingPolicy: RoutingPolicy = {\n onRouteConflict() {\n return \"keep_existing\";\n },\n};\n\nexport function toRouteConflictError(input: {\n toolId: string;\n kept: ToolRouteRecord;\n dropped: ToolRouteRecord;\n}): KontextError {\n return new KontextError(\n `Route conflict for tool \"${input.toolId}\". Keeping backend \"${input.kept.backendId}\" and dropping \"${input.dropped.backendId}\".`,\n \"kontext_tool_route_conflict\",\n {\n meta: {\n toolId: input.toolId,\n keptBackendId: input.kept.backendId,\n keptSource: input.kept.source,\n keptIntegrationId: input.kept.integrationId,\n droppedBackendId: input.dropped.backendId,\n droppedSource: input.dropped.source,\n droppedIntegrationId: input.dropped.integrationId,\n },\n },\n );\n}\n","import type { ClientState } from \"../../index.js\";\nimport type { KontextError } from \"../../../errors.js\";\n\nexport type KontextOrchestratorState = ClientState;\n\ntype OrchestratorEvent = \"stateChange\" | \"error\";\n\ntype ListenerMap = {\n stateChange: (state: KontextOrchestratorState) => void;\n error: (error: KontextError) => void;\n};\n\nexport interface OrchestratorStateController {\n readonly state: KontextOrchestratorState;\n setState(next: KontextOrchestratorState): void;\n emitError(error: KontextError): void;\n on(event: \"stateChange\", handler: ListenerMap[\"stateChange\"]): () => void;\n on(event: \"error\", handler: ListenerMap[\"error\"]): () => void;\n}\n\nexport function createOrchestratorStateController(input: {\n initialState?: KontextOrchestratorState;\n onStateChange?: (state: KontextOrchestratorState) => void;\n}): OrchestratorStateController {\n let state: KontextOrchestratorState = input.initialState ?? \"idle\";\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const listeners = new Map<OrchestratorEvent, Set<(...args: any[]) => void>>();\n\n function setState(next: KontextOrchestratorState): void {\n if (state === next) return;\n state = next;\n\n try {\n input.onStateChange?.(next);\n } catch {\n // Ignore user callback failures.\n }\n\n const handlers = listeners.get(\"stateChange\");\n if (!handlers) return;\n for (const handler of handlers) {\n try {\n handler(next);\n } catch {\n // Ignore listener failures.\n }\n }\n }\n\n function emitError(error: KontextError): void {\n const handlers = listeners.get(\"error\");\n if (!handlers) return;\n for (const handler of handlers) {\n try {\n handler(error);\n } catch {\n // Ignore listener failures.\n }\n }\n }\n\n function on(\n event: \"stateChange\" | \"error\",\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n handler: (...args: any[]) => void,\n ): () => void {\n if (!listeners.has(event)) {\n listeners.set(event, new Set());\n }\n listeners.get(event)!.add(handler);\n return () => {\n listeners.get(event)?.delete(handler);\n };\n }\n\n return {\n get state() {\n return state;\n },\n setState,\n emitError,\n on,\n };\n}\n","import { AuthorizationRequiredError, KontextError } from \"../../errors.js\";\nimport type { RuntimeIntegrationRecord } from \"../../mcp/client.js\";\nimport type { KontextStorage } from \"../../storage/types.js\";\nimport { createStorageKey, StorageKeys } from \"../../storage/types.js\";\n\ntype StoredAccessToken = {\n access_token?: string;\n expires_in?: number | string;\n issued_at?: number | string;\n token_type?: string;\n};\n\nfunction hasFreshStoredToken(\n tokens: StoredAccessToken | undefined,\n skewMs = 30_000,\n): boolean {\n if (!tokens?.access_token) return false;\n const expiresIn =\n typeof tokens.expires_in === \"number\"\n ? tokens.expires_in\n : Number(tokens.expires_in);\n const issuedAt =\n typeof tokens.issued_at === \"number\"\n ? tokens.issued_at\n : Number(tokens.issued_at);\n\n if (!Number.isFinite(expiresIn) || !Number.isFinite(issuedAt)) {\n return false;\n }\n\n const expiresAt = issuedAt + expiresIn * 1000;\n return Date.now() + skewMs < expiresAt;\n}\n\nexport interface TokenManager {\n tokenStorageKey(sessionKey: string): string;\n ensureInternalResourceToken(\n integration: RuntimeIntegrationRecord,\n options?: { forceExchange?: boolean },\n ): Promise<void>;\n}\n\nexport function createTokenManager(input: {\n clientId: string;\n baseSessionKey: string;\n gatewaySessionKey: string;\n serverUrl: string;\n storage: KontextStorage;\n}): TokenManager {\n const pendingInternalTokenExchange = new Map<string, Promise<void>>();\n\n function tokenStorageKey(sessionKey: string): string {\n return createStorageKey(input.clientId, sessionKey, StorageKeys.TOKENS);\n }\n\n async function readGatewayTokens(): Promise<{\n subjectToken: string | null;\n }> {\n const identityTokens = await input.storage.getJson<{\n access_token?: string;\n }>(\n createStorageKey(\n input.clientId,\n input.gatewaySessionKey,\n StorageKeys.IDENTITY_TOKENS,\n ),\n );\n const gatewayTokens = await input.storage.getJson<{\n access_token?: string;\n }>(tokenStorageKey(input.gatewaySessionKey));\n\n return {\n subjectToken:\n identityTokens?.access_token ?? gatewayTokens?.access_token ?? null,\n };\n }\n\n async function ensureInternalResourceToken(\n integration: RuntimeIntegrationRecord,\n options?: { forceExchange?: boolean },\n ): Promise<void> {\n const internalSessionKey = `${input.baseSessionKey}:internal:${integration.id}`;\n if (!options?.forceExchange) {\n const existingToken = await input.storage.getJson<StoredAccessToken>(\n tokenStorageKey(internalSessionKey),\n );\n if (hasFreshStoredToken(existingToken)) {\n return;\n }\n }\n\n const pending = pendingInternalTokenExchange.get(integration.id);\n if (pending) {\n return await pending;\n }\n\n const exchangePromise = (async () => {\n const { subjectToken: gatewaySubjectToken } = await readGatewayTokens();\n if (!gatewaySubjectToken) {\n return;\n }\n\n const body = new URLSearchParams({\n grant_type: \"urn:ietf:params:oauth:grant-type:token-exchange\",\n subject_token_type: \"urn:ietf:params:oauth:token-type:access_token\",\n subject_token: gatewaySubjectToken,\n resource: integration.url,\n client_id: input.clientId,\n });\n\n const response = await fetch(`${input.serverUrl}/oauth2/token`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n },\n body: body.toString(),\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 exchange gateway token for internal resource \"${integration.id}\": HTTP ${response.status}`,\n \"kontext_token_exchange_failed\",\n {\n statusCode: response.status,\n meta: {\n integrationId: integration.id,\n resource: integration.url,\n },\n },\n );\n }\n\n const exchanged = (await response.json()) as {\n access_token?: string;\n token_type?: string;\n expires_in?: number;\n refresh_token?: string;\n scope?: string;\n };\n\n if (!exchanged.access_token || !exchanged.token_type) {\n throw new KontextError(\n `Token exchange returned an invalid payload for integration \"${integration.id}\".`,\n \"kontext_token_exchange_failed\",\n {\n meta: {\n integrationId: integration.id,\n resource: integration.url,\n },\n },\n );\n }\n\n await input.storage.setJson(tokenStorageKey(internalSessionKey), {\n ...exchanged,\n issued_at: Date.now(),\n });\n })();\n\n pendingInternalTokenExchange.set(integration.id, exchangePromise);\n try {\n await exchangePromise;\n } finally {\n pendingInternalTokenExchange.delete(integration.id);\n }\n }\n\n return {\n tokenStorageKey,\n ensureInternalResourceToken,\n };\n}\n","import type { KontextClient } from \"../index.js\";\nimport type { RuntimeIntegrationRecord } from \"../../mcp/client.js\";\nimport {\n sortInternalIntegrations,\n type RoutingBackend,\n} from \"./internal/backends.js\";\n\nexport type InternalClientEntry = {\n integration: RuntimeIntegrationRecord;\n backendId: string;\n client: KontextClient;\n unsubscribeState: () => void;\n unsubscribeError: () => void;\n};\n\ntype InternalClientFactoryResult = {\n backend: RoutingBackend;\n client: KontextClient;\n unsubscribeState: () => void;\n unsubscribeError: () => void;\n};\n\nexport interface InternalClientRegistry {\n readonly size: number;\n entries(): IterableIterator<[string, InternalClientEntry]>;\n values(): IterableIterator<InternalClientEntry>;\n keys(): IterableIterator<string>;\n get(integrationId: string): InternalClientEntry | undefined;\n sync(discovered: RuntimeIntegrationRecord[]): Promise<void>;\n missingResolved(resolvedIntegrations: Set<string>): string[];\n dispose(mode: \"disconnect\" | \"signOut\"): Promise<void>;\n}\n\nexport function createInternalClientRegistry(input: {\n backends: Map<string, RoutingBackend>;\n createClient: (\n integration: RuntimeIntegrationRecord,\n ) => InternalClientFactoryResult;\n}): InternalClientRegistry {\n const internalClients = new Map<string, InternalClientEntry>();\n\n async function remove(integrationId: string): Promise<void> {\n const existing = internalClients.get(integrationId);\n if (!existing) return;\n\n existing.unsubscribeState();\n existing.unsubscribeError();\n internalClients.delete(integrationId);\n input.backends.delete(existing.backendId);\n\n try {\n await existing.client.disconnect();\n } catch {\n // Best effort disconnect.\n }\n }\n\n async function sync(discovered: RuntimeIntegrationRecord[]): Promise<void> {\n const sortedInternal = sortInternalIntegrations(discovered);\n const desiredById = new Map(sortedInternal.map((item) => [item.id, item]));\n\n for (const [integrationId, existing] of internalClients) {\n const next = desiredById.get(integrationId);\n if (!next) {\n await remove(integrationId);\n continue;\n }\n\n if (existing.integration.url !== next.url) {\n await remove(integrationId);\n }\n }\n\n for (const integration of sortedInternal) {\n const existing = internalClients.get(integration.id);\n if (existing) {\n existing.integration = integration;\n\n const backend = input.backends.get(existing.backendId);\n if (backend) {\n backend.integrationName = integration.name;\n }\n continue;\n }\n\n const created = input.createClient(integration);\n input.backends.set(created.backend.backendId, created.backend);\n internalClients.set(integration.id, {\n integration,\n backendId: created.backend.backendId,\n client: created.client,\n unsubscribeState: created.unsubscribeState,\n unsubscribeError: created.unsubscribeError,\n });\n }\n }\n\n function missingResolved(resolvedIntegrations: Set<string>): string[] {\n const missing: string[] = [];\n for (const integrationId of internalClients.keys()) {\n if (!resolvedIntegrations.has(integrationId)) {\n missing.push(integrationId);\n }\n }\n return missing;\n }\n\n async function dispose(mode: \"disconnect\" | \"signOut\"): Promise<void> {\n const entries = [...internalClients.values()];\n internalClients.clear();\n\n for (const backend of [...input.backends.values()]) {\n if (backend.source === \"internal\") {\n input.backends.delete(backend.backendId);\n }\n }\n\n await Promise.all(\n entries.map(async (entry) => {\n entry.unsubscribeState();\n entry.unsubscribeError();\n try {\n if (mode === \"signOut\") {\n await entry.client.auth.signOut();\n } else {\n await entry.client.disconnect();\n }\n } catch {\n // Best effort shutdown.\n }\n }),\n );\n }\n\n return {\n get size() {\n return internalClients.size;\n },\n entries() {\n return internalClients.entries();\n },\n values() {\n return internalClients.values();\n },\n keys() {\n return internalClients.keys();\n },\n get(integrationId: string) {\n return internalClients.get(integrationId);\n },\n sync,\n missingResolved,\n dispose,\n };\n}\n","/**\n * KontextOrchestrator — unified mixed-mode client facade.\n *\n * Combines:\n * - Gateway-routed tools (gateway_remote_mcp)\n * - Direct internal MCP tools (internal_mcp_credentials)\n *\n * into a single tool listing/execution surface.\n */\n\nimport {\n createSingleEndpointKontextClient,\n type ConnectSessionResult,\n type IntegrationInfo,\n type KontextClient,\n type KontextClientConfig,\n type KontextTool,\n type ToolResult,\n} from \"../index.js\";\nimport {\n normalizeKontextServerUrl,\n type RuntimeIntegrationRecord,\n} from \"../../mcp/client.js\";\nimport { MemoryStorage } from \"../../storage/memory.js\";\nimport type { KontextStorage } from \"../../storage/types.js\";\nimport {\n AuthorizationRequiredError,\n ConfigError,\n KontextError,\n isKontextError,\n isNetworkError,\n translateError,\n} from \"../../errors.js\";\nimport {\n createGatewayBackend,\n createInternalBackend,\n gatewayBackendId,\n internalBackendId,\n type RoutingBackend,\n} from \"./internal/backends.js\";\nimport { RouteInventoryStore } from \"./internal/inventory.js\";\nimport type {\n RouteConflictRecord,\n RouteInventoryCandidate,\n ToolRouteRecord,\n} from \"./internal/routes.js\";\nimport {\n defaultRoutingPolicy,\n toRouteConflictError,\n} from \"./internal/policy.js\";\nimport {\n createOrchestratorStateController,\n type KontextOrchestratorState,\n} from \"./internal/state.js\";\nimport { createTokenManager } from \"./token-manager.js\";\nimport {\n createInternalClientRegistry,\n type InternalClientEntry,\n} from \"./internal-client-registry.js\";\n\nexport type { KontextOrchestratorState };\n\nexport interface KontextOrchestratorConfig {\n clientId: string;\n redirectUri: string;\n serverUrl?: string;\n storage?: KontextStorage;\n sessionKey?: string;\n onAuthRequired: KontextClientConfig[\"onAuthRequired\"];\n onIntegrationRequired?: KontextClientConfig[\"onIntegrationRequired\"];\n onStateChange?: (state: KontextOrchestratorState) => void;\n}\n\nexport interface KontextOrchestrator {\n readonly state: KontextOrchestratorState;\n\n connect(): Promise<void>;\n disconnect(): Promise<void>;\n getConnectPageUrl(): Promise<ConnectSessionResult>;\n\n readonly auth: {\n signIn(): Promise<void>;\n signOut(): Promise<void>;\n handleCallback(url: string | URL): Promise<void>;\n isCallback(url: string | URL): boolean;\n readonly isAuthenticated: boolean;\n };\n\n readonly integrations: {\n list(): Promise<IntegrationInfo[]>;\n };\n\n readonly tools: {\n list(options?: { limit?: number }): Promise<KontextTool[]>;\n execute(\n toolId: string,\n args?: Record<string, unknown>,\n ): Promise<ToolResult>;\n };\n\n on(\n event: \"stateChange\",\n handler: (state: KontextOrchestratorState) => void,\n ): () => void;\n on(event: \"error\", handler: (error: KontextError) => void): () => void;\n\n readonly mcp: KontextClient[\"mcp\"];\n}\n\ntype ErrorContext = {\n backendId?: string;\n source?: \"gateway\" | \"internal\";\n integrationId?: string;\n operation: string;\n toolId?: string;\n};\n\nfunction isTransientError(err: unknown): boolean {\n if (err instanceof Error && isNetworkError(err)) {\n return true;\n }\n\n if (isKontextError(err)) {\n if (err.code === \"kontext_network_error\") return true;\n if (err.statusCode === 429) return true;\n if (typeof err.statusCode === \"number\" && err.statusCode >= 500) {\n return true;\n }\n return false;\n }\n\n if (typeof err === \"object\" && err !== null) {\n const errObj = err as { status?: unknown; statusCode?: unknown };\n const maybeStatus = errObj.statusCode ?? errObj.status;\n const status = typeof maybeStatus === \"number\" ? maybeStatus : undefined;\n if (status === 429 || (typeof status === \"number\" && status >= 500)) {\n return true;\n }\n }\n\n return false;\n}\n\nasync function withTransientRetry<T>(\n operation: () => Promise<T>,\n maxRetries = 1,\n): Promise<T> {\n const retryDelayMs = 250;\n for (let attempt = 0; attempt <= maxRetries; attempt += 1) {\n try {\n return await operation();\n } catch (err) {\n if (attempt >= maxRetries || !isTransientError(err)) {\n throw err;\n }\n await new Promise((resolve) => setTimeout(resolve, retryDelayMs));\n }\n }\n\n throw new Error(\"Transient retry loop exhausted unexpectedly.\");\n}\n\nfunction toKontextError(err: unknown, context?: ErrorContext): KontextError {\n const contextMeta = context ? { ...context } : undefined;\n const mergeMeta = (\n base?: Record<string, unknown>,\n ): Record<string, unknown> =>\n contextMeta ? { ...(base ?? {}), ...contextMeta } : (base ?? {});\n\n // Delegate core classification to translateError (handles KontextError pass-through,\n // MCP JSON-RPC codes, HTTP status, unauthorized, network errors)\n const translated = translateError(err);\n\n // If no context to add, return as-is\n if (!contextMeta) {\n return translated;\n }\n\n // Clone to add context meta without mutating shared instances\n const cloned = Object.create(\n Object.getPrototypeOf(translated),\n ) as KontextError;\n Object.defineProperties(cloned, Object.getOwnPropertyDescriptors(translated));\n Object.defineProperty(cloned, \"meta\", {\n value: mergeMeta(translated.meta),\n enumerable: true,\n writable: true,\n configurable: true,\n });\n return cloned;\n}\n\nfunction isAuthorizationRequired(err: unknown): boolean {\n if (err instanceof AuthorizationRequiredError) return true;\n if (isKontextError(err)) {\n return err.code === \"kontext_authorization_required\";\n }\n if (typeof err === \"object\" && err !== null) {\n return (\n (err as { code?: unknown }).code === \"kontext_authorization_required\"\n );\n }\n return false;\n}\n\nfunction isTokenExchangeFailure(err: unknown): boolean {\n if (isKontextError(err)) {\n return err.code === \"kontext_token_exchange_failed\";\n }\n if (typeof err === \"object\" && err !== null) {\n return (err as { code?: unknown }).code === \"kontext_token_exchange_failed\";\n }\n return false;\n}\n\nfunction isAuthRecoveryRequired(err: unknown): boolean {\n return isAuthorizationRequired(err) || isTokenExchangeFailure(err);\n}\nexport function createKontextOrchestrator(\n config: KontextOrchestratorConfig,\n): KontextOrchestrator {\n if (!config.clientId) {\n throw new ConfigError(\n \"clientId is required. Pass it in KontextOrchestratorConfig.\",\n \"kontext_config_missing_client_id\",\n );\n }\n if (!config.redirectUri) {\n throw new ConfigError(\n \"redirectUri is required. Set it to the URL where OAuth should redirect after authorization.\",\n \"kontext_config_missing_redirect_uri\",\n );\n }\n if (!config.onAuthRequired) {\n throw new ConfigError(\n \"onAuthRequired callback is required. Provide a function that opens the OAuth URL.\",\n \"kontext_config_missing_auth_handler\",\n );\n }\n\n const baseSessionKey = config.sessionKey ?? \"default\";\n const serverUrl = normalizeKontextServerUrl(\n config.serverUrl ?? \"https://api.kontext.dev\",\n );\n const sharedStorage = config.storage ?? new MemoryStorage();\n const gatewaySessionKey = `${baseSessionKey}:gateway`;\n\n const authSourceQueue: Array<\"gateway\" | string> = [];\n const stateController = createOrchestratorStateController({\n initialState: \"idle\",\n onStateChange: config.onStateChange,\n });\n\n const routeInventory = new RouteInventoryStore();\n const routingPolicy = defaultRoutingPolicy;\n\n const runtimeIntegrations = new Map<string, RuntimeIntegrationRecord>();\n const backends = new Map<string, RoutingBackend>();\n const managedInternalOps = new Map<string, number>();\n const resolvedInternalListings = new Set<string>();\n\n const tokenManager = createTokenManager({\n clientId: config.clientId,\n baseSessionKey,\n gatewaySessionKey,\n serverUrl,\n storage: sharedStorage,\n });\n\n let pendingIntegrationRefresh: Promise<RuntimeIntegrationRecord[]> | null =\n null;\n\n const gatewayClient = createSingleEndpointKontextClient({\n clientId: config.clientId,\n redirectUri: config.redirectUri,\n serverUrl: config.serverUrl,\n storage: sharedStorage,\n sessionKey: gatewaySessionKey,\n onAuthRequired: async (url) => {\n authSourceQueue.push(\"gateway\");\n return await config.onAuthRequired(url);\n },\n onIntegrationRequired: config.onIntegrationRequired,\n });\n\n const gatewayBackend = createGatewayBackend(gatewayClient);\n backends.set(gatewayBackendId(), gatewayBackend);\n\n const gatewayStateUnsubscribe = gatewayClient.on(\"stateChange\", (state) => {\n if (state === \"needs_auth\") {\n stateController.setState(\"needs_auth\");\n }\n });\n const gatewayErrorUnsubscribe = gatewayClient.on(\"error\", (error) => {\n const translated = toKontextError(error, {\n backendId: gatewayBackendId(),\n source: \"gateway\",\n operation: \"client_error_event\",\n });\n stateController.emitError(translated);\n if (isAuthRecoveryRequired(translated)) {\n stateController.setState(\"needs_auth\");\n }\n });\n\n const ensureInternalResourceToken = tokenManager.ensureInternalResourceToken;\n\n function isInternalOpManaged(integrationId: string): boolean {\n return (managedInternalOps.get(integrationId) ?? 0) > 0;\n }\n\n async function runManagedInternalOp<T>(\n integrationId: string,\n operation: () => Promise<T>,\n ): Promise<T> {\n managedInternalOps.set(\n integrationId,\n (managedInternalOps.get(integrationId) ?? 0) + 1,\n );\n try {\n return await operation();\n } finally {\n const next = (managedInternalOps.get(integrationId) ?? 1) - 1;\n if (next <= 0) {\n managedInternalOps.delete(integrationId);\n } else {\n managedInternalOps.set(integrationId, next);\n }\n }\n }\n\n function createInternalClient(integration: RuntimeIntegrationRecord): {\n backend: RoutingBackend;\n client: KontextClient;\n unsubscribeState: () => void;\n unsubscribeError: () => void;\n } {\n const client = createSingleEndpointKontextClient({\n clientId: config.clientId,\n redirectUri: config.redirectUri,\n url: integration.url,\n serverUrl: config.serverUrl,\n storage: sharedStorage,\n sessionKey: `${baseSessionKey}:internal:${integration.id}`,\n onAuthRequired: async (url) => {\n authSourceQueue.push(integration.id);\n return await config.onAuthRequired(url);\n },\n onIntegrationRequired: config.onIntegrationRequired,\n });\n\n const unsubscribeState = client.on(\"stateChange\", (state) => {\n if (state === \"needs_auth\") {\n stateController.setState(\"needs_auth\");\n }\n });\n const unsubscribeError = client.on(\"error\", (error) => {\n const translated = toKontextError(error, {\n backendId: internalBackendId(integration.id),\n source: \"internal\",\n integrationId: integration.id,\n operation: \"client_error_event\",\n });\n if (\n isInternalOpManaged(integration.id) &&\n isAuthorizationRequired(translated)\n ) {\n return;\n }\n if (isAuthRecoveryRequired(translated)) {\n stateController.setState(\"needs_auth\");\n return;\n }\n stateController.emitError(translated);\n });\n\n const backend = createInternalBackend({ integration, client });\n\n return { backend, client, unsubscribeState, unsubscribeError };\n }\n\n const internalClientRegistry = createInternalClientRegistry({\n backends,\n createClient: createInternalClient,\n });\n\n async function refreshIntegrationInventory(\n force = false,\n ): Promise<RuntimeIntegrationRecord[]> {\n if (pendingIntegrationRefresh) {\n if (!force) {\n return await pendingIntegrationRefresh;\n }\n // Serialize forced refreshes to avoid concurrent shared-state updates.\n await pendingIntegrationRefresh;\n }\n\n const refreshPromise = (async () => {\n const items = await withTransientRetry(\n async () => await gatewayClient.mcp.listRuntimeIntegrations(),\n );\n await applyRuntimeIntegrations(items);\n return items;\n })();\n pendingIntegrationRefresh = refreshPromise;\n\n try {\n return await refreshPromise;\n } finally {\n if (pendingIntegrationRefresh === refreshPromise) {\n pendingIntegrationRefresh = null;\n }\n }\n }\n\n async function applyRuntimeIntegrations(\n integrations: RuntimeIntegrationRecord[],\n ): Promise<void> {\n runtimeIntegrations.clear();\n for (const item of integrations) {\n runtimeIntegrations.set(item.id, item);\n }\n await internalClientRegistry.sync(integrations);\n }\n\n async function buildInventoryCandidates(options?: {\n limit?: number;\n runtimeIntegrations?: RuntimeIntegrationRecord[];\n }): Promise<RouteInventoryCandidate[]> {\n const candidates: RouteInventoryCandidate[] = [];\n resolvedInternalListings.clear();\n const pendingInternalAuthRetries = new Set<string>();\n\n const gatewayTools = await gatewayClient.tools.list(options);\n for (const tool of gatewayTools) {\n candidates.push({\n tool,\n route: {\n toolId: tool.id,\n backendId: gatewayBackendId(),\n source: \"gateway\",\n backendToolId: tool.id,\n },\n });\n }\n\n if (options?.runtimeIntegrations) {\n await applyRuntimeIntegrations(options.runtimeIntegrations);\n } else {\n await refreshIntegrationInventory();\n }\n\n const sortedInternalEntries = [...internalClientRegistry.values()].sort(\n (a, b) => a.integration.id.localeCompare(b.integration.id),\n );\n\n const addInternalToolsForEntry = async (entry: InternalClientEntry) => {\n const internalTools = await withTransientRetry(\n async () =>\n await runManagedInternalOp(entry.integration.id, () =>\n entry.client.tools.list(),\n ),\n );\n resolvedInternalListings.add(entry.integration.id);\n for (const tool of internalTools) {\n const backendToolId = tool.id || tool.name;\n const unifiedId = `${entry.integration.id}:${tool.name}`;\n\n candidates.push({\n tool: {\n id: unifiedId,\n name: tool.name,\n description: tool.description,\n inputSchema: tool.inputSchema,\n server: {\n id: entry.integration.id,\n name: entry.integration.name,\n },\n },\n route: {\n toolId: unifiedId,\n backendId: entry.backendId,\n source: \"internal\",\n backendToolId,\n integrationId: entry.integration.id,\n },\n });\n }\n };\n\n for (const entry of sortedInternalEntries) {\n try {\n await ensureInternalResourceToken(entry.integration);\n await addInternalToolsForEntry(entry);\n } catch (err) {\n const translated = toKontextError(err, {\n backendId: entry.backendId,\n source: \"internal\",\n integrationId: entry.integration.id,\n operation: \"tools.list\",\n });\n if (isAuthorizationRequired(translated)) {\n pendingInternalAuthRetries.add(entry.integration.id);\n continue;\n }\n if (isTokenExchangeFailure(translated)) {\n stateController.setState(\"needs_auth\");\n }\n stateController.emitError(translated);\n }\n }\n\n if (pendingInternalAuthRetries.size > 0) {\n let hasUnresolvedAuth = false;\n for (const integrationId of pendingInternalAuthRetries) {\n const entry = internalClientRegistry.get(integrationId);\n if (!entry) continue;\n\n try {\n await ensureInternalResourceToken(entry.integration, {\n forceExchange: true,\n });\n await runManagedInternalOp(integrationId, async () => {\n await entry.client.disconnect();\n await entry.client.connect();\n });\n await addInternalToolsForEntry(entry);\n } catch (err) {\n const translated = toKontextError(err);\n if (isAuthRecoveryRequired(translated)) {\n hasUnresolvedAuth = true;\n if (isTokenExchangeFailure(translated)) {\n stateController.emitError(translated);\n }\n continue;\n }\n stateController.emitError(translated);\n }\n }\n\n if (hasUnresolvedAuth) {\n stateController.setState(\"needs_auth\");\n } else if (\n stateController.state === \"needs_auth\" &&\n gatewayClient.state === \"ready\"\n ) {\n stateController.setState(\"ready\");\n }\n }\n\n return candidates;\n }\n\n async function buildToolInventory(options?: {\n limit?: number;\n runtimeIntegrations?: RuntimeIntegrationRecord[];\n }): Promise<{\n tools: KontextTool[];\n conflicts: RouteConflictRecord[];\n }> {\n const inventoryKey = JSON.stringify({\n limit: options?.limit ?? null,\n runtimeIntegrations:\n options?.runtimeIntegrations\n ?.map((integration) => integration.id)\n .sort() ?? null,\n });\n const snapshot = await routeInventory.build(\n async () => await buildInventoryCandidates(options),\n {\n key: inventoryKey,\n onConflict: (existing, incoming) =>\n routingPolicy.onRouteConflict({\n toolId: existing.toolId,\n existing,\n incoming,\n }),\n },\n );\n return {\n tools: snapshot.tools,\n conflicts: snapshot.conflicts,\n };\n }\n\n function emitRouteConflicts(conflicts: RouteConflictRecord[]): void {\n for (const conflict of conflicts) {\n stateController.emitError(\n toRouteConflictError({\n toolId: conflict.toolId,\n kept: conflict.kept,\n dropped: conflict.dropped,\n }),\n );\n }\n }\n\n function getInternalIntegrationsMissingTools(): string[] {\n return internalClientRegistry.missingResolved(resolvedInternalListings);\n }\n\n async function disposeInternalClients(\n mode: \"disconnect\" | \"signOut\",\n ): Promise<void> {\n await internalClientRegistry.dispose(mode);\n }\n\n async function ensureConnected(): Promise<void> {\n if (stateController.state === \"ready\") return;\n if (\n stateController.state === \"needs_auth\" &&\n gatewayClient.state === \"ready\"\n ) {\n return;\n }\n\n stateController.setState(\"connecting\");\n\n try {\n await gatewayClient.connect();\n await refreshIntegrationInventory(true);\n stateController.setState(\"ready\");\n } catch (err) {\n const translated = toKontextError(err, {\n backendId: gatewayBackendId(),\n source: \"gateway\",\n operation: \"connect\",\n });\n if (isAuthRecoveryRequired(translated)) {\n stateController.setState(\"needs_auth\");\n } else {\n stateController.setState(\"failed\");\n }\n stateController.emitError(translated);\n throw translated;\n }\n }\n\n async function routeForExecution(toolId: string): Promise<ToolRouteRecord> {\n let route = routeInventory.routeFor(toolId);\n if (route) return route;\n\n const inventory = await buildToolInventory();\n emitRouteConflicts(inventory.conflicts);\n route = routeInventory.routeFor(toolId);\n if (route) return route;\n\n throw new KontextError(\n `Unknown tool \"${toolId}\". Call tools.list() to refresh available tools.`,\n \"kontext_tool_not_found\",\n { meta: { toolId } },\n );\n }\n\n const orchestrator: KontextOrchestrator = {\n get state() {\n return stateController.state;\n },\n\n async connect() {\n await ensureConnected();\n },\n\n async disconnect() {\n await disposeInternalClients(\"disconnect\");\n runtimeIntegrations.clear();\n routeInventory.reset();\n authSourceQueue.length = 0;\n await gatewayClient.disconnect();\n stateController.setState(\"idle\");\n },\n\n async getConnectPageUrl(): Promise<ConnectSessionResult> {\n await ensureConnected();\n return await gatewayClient.getConnectPageUrl();\n },\n\n auth: {\n async signIn() {\n if (\n stateController.state === \"needs_auth\" &&\n gatewayClient.state === \"ready\"\n ) {\n await refreshIntegrationInventory(true);\n\n let unresolvedInternalAuth = false;\n for (const [\n integrationId,\n entry,\n ] of internalClientRegistry.entries()) {\n try {\n await runManagedInternalOp(integrationId, () =>\n entry.client.auth.signIn(),\n );\n } catch (err) {\n const translated = toKontextError(err);\n if (isAuthorizationRequired(translated)) {\n unresolvedInternalAuth = true;\n continue;\n }\n stateController.emitError(translated);\n }\n }\n\n const inventory = await buildToolInventory();\n emitRouteConflicts(inventory.conflicts);\n const missingInternal = getInternalIntegrationsMissingTools();\n if (!unresolvedInternalAuth && missingInternal.length === 0) {\n stateController.setState(\"ready\");\n }\n return;\n }\n\n await ensureConnected();\n },\n\n async signOut() {\n await disposeInternalClients(\"signOut\");\n runtimeIntegrations.clear();\n routeInventory.reset();\n authSourceQueue.length = 0;\n await gatewayClient.auth.signOut();\n stateController.setState(\"idle\");\n },\n\n async handleCallback(url: string | URL) {\n if (internalClientRegistry.size === 0) {\n try {\n await refreshIntegrationInventory(true);\n } catch (err) {\n stateController.emitError(\n toKontextError(err, {\n backendId: gatewayBackendId(),\n source: \"gateway\",\n operation: \"auth.handleCallback.preload\",\n }),\n );\n }\n }\n\n const ordered: Array<{\n client: KontextClient;\n sourceId?: \"gateway\" | string;\n }> = [];\n\n for (const sourceId of authSourceQueue) {\n if (sourceId === \"gateway\") {\n ordered.push({ client: gatewayClient, sourceId });\n continue;\n }\n const active = internalClientRegistry.get(sourceId);\n if (active) {\n ordered.push({ client: active.client, sourceId });\n }\n }\n\n if (gatewayClient.auth.isCallback(url)) {\n ordered.push({ client: gatewayClient });\n }\n\n for (const entry of internalClientRegistry.values()) {\n if (entry.client.auth.isCallback(url)) {\n ordered.push({ client: entry.client });\n }\n }\n\n ordered.push({ client: gatewayClient });\n ordered.push(\n ...[...internalClientRegistry.values()]\n .sort((a, b) => a.integration.id.localeCompare(b.integration.id))\n .map((entry) => ({ client: entry.client })),\n );\n\n const unique: Array<{\n client: KontextClient;\n sourceId?: \"gateway\" | string;\n }> = [];\n const seen = new Set<KontextClient>();\n for (const entry of ordered) {\n if (seen.has(entry.client)) continue;\n seen.add(entry.client);\n unique.push(entry);\n }\n\n let handledBy:\n | {\n client: KontextClient;\n sourceId?: \"gateway\" | string;\n }\n | undefined;\n let lastError: unknown = undefined;\n\n for (const entry of unique) {\n try {\n await entry.client.auth.handleCallback(url);\n handledBy = entry;\n break;\n } catch (err) {\n lastError = err;\n }\n }\n\n if (handledBy) {\n for (let idx = authSourceQueue.length - 1; idx >= 0; idx -= 1) {\n const sourceId = authSourceQueue[idx]!;\n const sourceClient =\n sourceId === \"gateway\"\n ? gatewayClient\n : internalClientRegistry.get(sourceId)?.client;\n if (sourceClient === handledBy.client) {\n authSourceQueue.splice(idx, 1);\n }\n }\n }\n\n if (!handledBy && lastError) {\n throw toKontextError(lastError, {\n backendId: gatewayBackendId(),\n source: \"gateway\",\n operation: \"auth.handleCallback\",\n });\n }\n\n try {\n await ensureConnected();\n } catch (err) {\n stateController.emitError(\n toKontextError(err, {\n backendId: gatewayBackendId(),\n source: \"gateway\",\n operation: \"post_callback_connect\",\n }),\n );\n }\n },\n\n isCallback(url: string | URL): boolean {\n if (gatewayClient.auth.isCallback(url)) return true;\n for (const entry of internalClientRegistry.values()) {\n if (entry.client.auth.isCallback(url)) return true;\n }\n return false;\n },\n\n get isAuthenticated(): boolean {\n return (\n stateController.state === \"ready\" ||\n gatewayClient.auth.isAuthenticated\n );\n },\n },\n\n integrations: {\n async list(): Promise<IntegrationInfo[]> {\n await ensureConnected();\n const discovered = await refreshIntegrationInventory(true);\n\n let gatewayStatuses: IntegrationInfo[] = [];\n try {\n gatewayStatuses = await gatewayClient.integrations.list();\n } catch (err) {\n stateController.emitError(\n toKontextError(err, {\n backendId: gatewayBackendId(),\n source: \"gateway\",\n operation: \"integrations.list\",\n }),\n );\n }\n const gatewayById = new Map(gatewayStatuses.map((i) => [i.id, i]));\n\n const needsInternalConnectLink = discovered.some(\n (i) =>\n i.category === \"internal_mcp_credentials\" &&\n !i.connection?.connected,\n );\n\n let sharedConnectUrl: string | undefined;\n if (needsInternalConnectLink) {\n try {\n sharedConnectUrl = (await gatewayClient.getConnectPageUrl())\n .connectUrl;\n } catch {\n sharedConnectUrl = undefined;\n }\n }\n\n return discovered.map((integration) => {\n const gatewayStatus = gatewayById.get(integration.id);\n const connected =\n gatewayStatus?.connected ??\n integration.connection?.connected ??\n false;\n const connectUrl =\n gatewayStatus?.connectUrl ??\n (!connected && integration.category === \"internal_mcp_credentials\"\n ? sharedConnectUrl\n : undefined);\n const reason =\n gatewayStatus?.reason ??\n (!connected && integration.category === \"internal_mcp_credentials\"\n ? \"credentials_required\"\n : undefined);\n\n return {\n id: integration.id,\n name: integration.name,\n connected,\n connectUrl,\n reason,\n };\n });\n },\n },\n\n tools: {\n async list(options?: { limit?: number }): Promise<KontextTool[]> {\n await ensureConnected();\n let inventory = await buildToolInventory(options);\n\n const missingInternal = getInternalIntegrationsMissingTools();\n if (missingInternal.length > 0) {\n const refreshed = await refreshIntegrationInventory(true);\n inventory = await buildToolInventory({\n ...options,\n runtimeIntegrations: refreshed,\n });\n }\n emitRouteConflicts(inventory.conflicts);\n\n const unresolvedInternal = getInternalIntegrationsMissingTools();\n if (\n stateController.state === \"needs_auth\" &&\n gatewayClient.state === \"ready\" &&\n unresolvedInternal.length === 0\n ) {\n stateController.setState(\"ready\");\n }\n\n return inventory.tools;\n },\n\n async execute(\n toolId: string,\n args?: Record<string, unknown>,\n ): Promise<ToolResult> {\n await ensureConnected();\n\n const route = await routeForExecution(toolId);\n\n try {\n if (route.source === \"gateway\") {\n return await gatewayClient.tools.execute(route.backendToolId, args);\n }\n\n const integrationId = route.integrationId;\n if (!integrationId) {\n throw new KontextError(\n `Route for tool \"${toolId}\" is missing integration metadata.`,\n \"kontext_tool_not_found\",\n { meta: { toolId, route } },\n );\n }\n\n let entry = internalClientRegistry.get(integrationId);\n if (!entry) {\n await refreshIntegrationInventory(true);\n entry = internalClientRegistry.get(integrationId);\n }\n if (!entry) {\n throw new KontextError(\n `Internal integration \"${integrationId}\" is no longer attached.`,\n \"kontext_tool_not_found\",\n { meta: { integrationId } },\n );\n }\n\n await ensureInternalResourceToken(entry.integration);\n try {\n const executeInternal = async () =>\n await withTransientRetry(\n async () =>\n await runManagedInternalOp(integrationId, () =>\n entry.client.tools.execute(route.backendToolId, args),\n ),\n );\n return await executeInternal();\n } catch (innerErr) {\n const innerTranslated = toKontextError(innerErr, {\n backendId: route.backendId,\n source: route.source,\n integrationId: route.integrationId,\n operation: \"tools.execute\",\n toolId,\n });\n throw innerTranslated;\n }\n } catch (err) {\n const translated = toKontextError(err, {\n backendId: route.backendId,\n source: route.source,\n integrationId: route.integrationId,\n operation: \"tools.execute\",\n toolId,\n });\n if (isAuthRecoveryRequired(translated)) {\n stateController.setState(\"needs_auth\");\n }\n stateController.emitError(translated);\n throw translated;\n }\n },\n },\n\n on(\n event: \"stateChange\" | \"error\",\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n handler: (...args: any[]) => void,\n ): () => void {\n if (event === \"stateChange\") {\n return stateController.on(\"stateChange\", handler);\n }\n return stateController.on(\"error\", handler);\n },\n\n get mcp() {\n return gatewayClient.mcp;\n },\n };\n\n // Preserve lifecycle subscriptions.\n void gatewayStateUnsubscribe;\n void gatewayErrorUnsubscribe;\n\n return orchestrator;\n}\n","/**\n * KontextClient — protocol-agnostic facade over KontextMcp.\n *\n * Hides all MCP internals (SEARCH_TOOLS, EXECUTE_TOOL, -32042) behind a\n * clean, typed API. Advanced users can access the underlying KontextMcp\n * via `client.mcp`.\n *\n * @example\n * ```typescript\n * import { createKontextClient } from '@kontext-dev/js-sdk';\n *\n * const client = createKontextClient({\n * clientId: 'your-client-id',\n * redirectUri: 'http://localhost:3000/callback',\n * onAuthRequired: (url) => open(url.toString()),\n * });\n *\n * await client.connect();\n * const tools = await client.tools.list();\n * const result = await client.tools.execute('github:repos', { query: 'mcp' });\n * ```\n *\n * @packageDocumentation\n */\n\nimport { KontextMcp } from \"../mcp/client.js\";\nimport type { KontextStorage } from \"../storage/types.js\";\nimport { parseIntegrationStatus } from \"./tool-utils.js\";\nimport { createKontextOrchestrator } from \"./orchestrator/index.js\";\nimport {\n AuthorizationRequiredError,\n KontextError,\n ConfigError,\n translateError,\n} from \"../errors.js\";\n\n// ============================================================================\n// Public types\n// ============================================================================\n\nexport type ClientState =\n | \"idle\"\n | \"connecting\"\n | \"ready\"\n | \"needs_auth\"\n | \"failed\";\n\nexport interface KontextClientConfig {\n clientId: string;\n redirectUri: 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 serverUrl?: string;\n storage?: KontextStorage;\n sessionKey?: string;\n\n onAuthRequired: (\n url: URL,\n ) => string | URL | void | Promise<string | URL | void>;\n onIntegrationRequired?: (\n url: string,\n info: { id: string; name?: string },\n ) => void | Promise<void>;\n onStateChange?: (state: ClientState) => void;\n}\n\nexport interface KontextTool {\n id: string;\n name: string;\n description?: string;\n inputSchema?: object;\n server?: { id: string; name?: string };\n}\n\nexport interface IntegrationInfo {\n id: string;\n name: string;\n connected: boolean;\n connectUrl?: string;\n reason?: string;\n}\n\nexport interface ToolResult {\n content: string;\n raw: unknown;\n}\n\nexport interface ConnectSessionResult {\n connectUrl: string;\n sessionId: string;\n expiresAt: string;\n}\n\nexport interface KontextClient {\n readonly state: ClientState;\n\n connect(): Promise<void>;\n disconnect(): Promise<void>;\n getConnectPageUrl(): Promise<ConnectSessionResult>;\n\n readonly auth: {\n signIn(): Promise<void>;\n signOut(): Promise<void>;\n handleCallback(url: string | URL): Promise<void>;\n isCallback(url: string | URL): boolean;\n readonly isAuthenticated: boolean;\n };\n\n readonly integrations: {\n list(): Promise<IntegrationInfo[]>;\n };\n\n readonly tools: {\n list(options?: { limit?: number }): Promise<KontextTool[]>;\n execute(\n toolId: string,\n args?: Record<string, unknown>,\n ): Promise<ToolResult>;\n };\n\n on(event: \"stateChange\", handler: (state: ClientState) => void): () => void;\n on(event: \"error\", handler: (error: KontextError) => void): () => void;\n\n /**\n * Advanced escape hatch to the raw MCP client.\n *\n * Note: In hybrid/orchestrator mode (`createKontextClient` called without\n * `url`), this is the gateway MCP client only. Tools from direct internal\n * integrations are exposed through `client.tools`, not through this property.\n */\n readonly mcp: KontextMcp;\n}\n\n// ============================================================================\n// Internal helpers — meta-tool detection & gateway parsing\n// ============================================================================\n\nconst META_TOOL_NAMES = new Set([\n \"SEARCH_TOOLS\",\n \"EXECUTE_TOOL\",\n \"REQUEST_CAPABILITY\",\n]);\n\nfunction hasMetaTools(tools: Array<{ name: string }>): boolean {\n let hasSearch = false;\n let hasExecute = false;\n for (const tool of tools) {\n if (tool.name === \"SEARCH_TOOLS\") hasSearch = true;\n if (tool.name === \"EXECUTE_TOOL\") hasExecute = true;\n }\n return hasSearch && hasExecute;\n}\n\ntype GatewayToolSummary = {\n id: string;\n name: string;\n description?: string;\n inputSchema?: unknown;\n server?: { id?: string; name?: string; url?: string };\n};\n\ntype GatewayToolError = {\n serverId: string;\n reason: string;\n serverName?: string;\n};\n\ntype McpContentItem = {\n type?: string;\n text?: string;\n resource?: { mimeType?: string; text?: string };\n};\n\nfunction extractJsonResourceText(result: unknown): string | null {\n if (!result || typeof result !== \"object\") return null;\n const content = (result as { content?: McpContentItem[] }).content;\n if (!Array.isArray(content)) return null;\n for (const item of content) {\n if (\n item.type === \"resource\" &&\n item.resource?.mimeType === \"application/json\" &&\n item.resource.text\n ) {\n return item.resource.text;\n }\n }\n return null;\n}\n\nfunction extractTextContent(result: unknown): string {\n if (!result || typeof result !== \"object\") return String(result ?? \"\");\n const r = result as { content?: McpContentItem[] };\n if (r.content && Array.isArray(r.content)) {\n const texts = r.content\n .filter((c) => c.type === \"text\" && c.text)\n .map((c) => c.text!);\n if (texts.length > 0) return texts.join(\"\\n\");\n\n // Meta-tool EXECUTE_TOOL responses are wrapped as resource JSON payloads.\n const resourceTexts = r.content\n .filter((c) => c.type === \"resource\" && c.resource?.text)\n .map((c) => c.resource!.text!);\n if (resourceTexts.length > 0) {\n return resourceTexts\n .map((text) => {\n try {\n return extractTextContent(JSON.parse(text));\n } catch {\n return text;\n }\n })\n .join(\"\\n\");\n }\n\n return JSON.stringify(r.content);\n }\n return JSON.stringify(result);\n}\n\nexport { translateError } from \"../errors.js\";\n\n// ============================================================================\n// Factory\n// ============================================================================\n\nexport function createSingleEndpointKontextClient(\n config: KontextClientConfig,\n): KontextClient {\n if (!config.clientId) {\n throw new ConfigError(\n \"clientId is required. Pass it in KontextClientConfig or set KONTEXT_CLIENT_ID.\",\n \"kontext_config_missing_client_id\",\n );\n }\n if (!config.redirectUri) {\n throw new ConfigError(\n \"redirectUri is required. Set it to the URL where OAuth should redirect after authorization.\",\n \"kontext_config_missing_redirect_uri\",\n );\n }\n if (!config.onAuthRequired) {\n throw new ConfigError(\n \"onAuthRequired callback is required. Provide a function that opens the OAuth URL.\",\n \"kontext_config_missing_auth_handler\",\n );\n }\n\n let _state: ClientState = \"idle\";\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const _listeners = new Map<string, Set<(...args: any[]) => void>>();\n let _metaToolMode: boolean | null = null;\n\n // Build KontextMcp config — route elicitation to onIntegrationRequired\n const mcp = new KontextMcp({\n clientId: config.clientId,\n url: config.url,\n server: config.serverUrl,\n redirectUri: config.redirectUri,\n storage: config.storage,\n sessionKey: config.sessionKey,\n onAuthRequired: config.onAuthRequired,\n // Route MCP elicitation to the high-level callback.\n // KontextMcp calls this then re-throws; client.tools.execute() catches\n // the re-thrown error and handles translation.\n onElicitationUrl: config.onIntegrationRequired\n ? (entry) => {\n config.onIntegrationRequired!(entry.url, {\n id: entry.integrationId ?? \"unknown\",\n name: entry.integrationName ?? entry.message,\n });\n }\n : undefined,\n });\n\n // -- State machine helpers --\n\n function setState(newState: ClientState) {\n if (_state === newState) return;\n _state = newState;\n try {\n config.onStateChange?.(newState);\n } catch {\n // Don't let listener errors break state transitions\n }\n const handlers = _listeners.get(\"stateChange\");\n if (handlers) {\n for (const handler of handlers) {\n try {\n handler(newState);\n } catch {\n // Don't let listener errors break state transitions\n }\n }\n }\n }\n\n function emitError(error: KontextError) {\n const handlers = _listeners.get(\"error\");\n if (handlers) {\n for (const handler of handlers) {\n try {\n handler(error);\n } catch {\n // Don't let listener errors mask the original error\n }\n }\n }\n }\n\n // -- Gateway tool helpers --\n\n async function fetchGatewayTools(limit = 100): Promise<{\n tools: GatewayToolSummary[];\n errors: GatewayToolError[];\n elicitations?: Array<{\n url: string;\n message?: string;\n integrationId?: string;\n integrationName?: string;\n }>;\n }> {\n const result = await mcp.callTool(\"SEARCH_TOOLS\", { limit });\n const jsonText = extractJsonResourceText(result);\n if (!jsonText) {\n throw new KontextError(\n \"SEARCH_TOOLS did not return JSON resource content. The server may not support the gateway protocol.\",\n \"kontext_tool_response_empty\",\n );\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(jsonText);\n } catch (e) {\n throw new KontextError(\n `SEARCH_TOOLS returned invalid JSON: ${e instanceof Error ? e.message : String(e)}`,\n \"kontext_tool_response_invalid_json\",\n );\n }\n if (Array.isArray(parsed)) {\n return { tools: parsed as GatewayToolSummary[], errors: [] };\n }\n if (parsed && typeof parsed === \"object\") {\n const obj = parsed as Record<string, unknown>;\n return {\n tools: Array.isArray(obj.items) ? obj.items : [],\n errors: Array.isArray(obj.errors) ? obj.errors : [],\n elicitations: Array.isArray(obj.elicitations)\n ? obj.elicitations\n : undefined,\n };\n }\n throw new KontextError(\n \"SEARCH_TOOLS response was not a JSON array or object. Check the server version.\",\n \"kontext_tool_response_unexpected\",\n );\n }\n\n function toKontextTool(tool: GatewayToolSummary): KontextTool {\n return {\n id: tool.id,\n name: tool.name,\n description: tool.description,\n inputSchema: tool.inputSchema as object | undefined,\n server: tool.server\n ? { id: tool.server.id ?? \"\", name: tool.server.name }\n : undefined,\n };\n }\n\n async function ensureConnected(): Promise<void> {\n if (_state === \"ready\" && mcp.isConnected) return;\n setState(\"connecting\");\n try {\n // listTools() triggers lazy connection inside KontextMcp\n const mcpTools = await mcp.listTools();\n _metaToolMode = hasMetaTools(mcpTools);\n setState(\"ready\");\n } catch (err) {\n const translated = translateError(err);\n if (translated instanceof AuthorizationRequiredError) {\n setState(\"needs_auth\");\n } else {\n setState(\"failed\");\n }\n emitError(translated);\n throw translated;\n }\n }\n\n // -- Public interface --\n\n const client: KontextClient = {\n get state() {\n return _state;\n },\n\n async connect() {\n await ensureConnected();\n },\n\n async disconnect() {\n await mcp.disconnect();\n _metaToolMode = null;\n setState(\"idle\");\n },\n\n async getConnectPageUrl(): Promise<ConnectSessionResult> {\n await ensureConnected();\n try {\n return await mcp.createConnectSession();\n } catch (err) {\n const translated = translateError(err);\n if (translated instanceof AuthorizationRequiredError) {\n setState(\"needs_auth\");\n }\n throw translated;\n }\n },\n\n auth: {\n async signIn() {\n await ensureConnected();\n },\n\n async signOut() {\n await mcp.clearAuth();\n _metaToolMode = null;\n setState(\"idle\");\n },\n\n async handleCallback(url: string | URL) {\n await mcp.handleCallback(url);\n try {\n await ensureConnected();\n } catch (err) {\n // Connection may not succeed yet — emit error but don't throw\n // since the callback itself was handled successfully\n emitError(translateError(err));\n }\n },\n\n isCallback(url: string | URL): boolean {\n return mcp.isCallback(url);\n },\n\n get isAuthenticated(): boolean {\n return _state === \"ready\" || mcp.isConnected;\n },\n },\n\n integrations: {\n async list(): Promise<IntegrationInfo[]> {\n await ensureConnected();\n try {\n const { tools, errors, elicitations } = await fetchGatewayTools();\n\n const statuses = parseIntegrationStatus(tools, errors, elicitations);\n\n // Enrich with reason from errors\n const errorMap = new Map(errors.map((e) => [e.serverId, e.reason]));\n return statuses.map((s) => {\n const reason = errorMap.get(s.id);\n return reason ? { ...s, reason } : s;\n });\n } catch (err) {\n const translated = translateError(err);\n if (translated instanceof AuthorizationRequiredError) {\n setState(\"needs_auth\");\n }\n throw translated;\n }\n },\n },\n\n tools: {\n async list(options?: { limit?: number }): Promise<KontextTool[]> {\n await ensureConnected();\n try {\n const mcpTools = await mcp.listTools();\n const nonMetaTools = mcpTools.filter(\n (t) => !META_TOOL_NAMES.has(t.name),\n );\n\n if (nonMetaTools.length > 0 || !hasMetaTools(mcpTools)) {\n _metaToolMode = false;\n return nonMetaTools.map((t) => ({\n id: t.name,\n name: t.name,\n description: t.description,\n inputSchema: t.inputSchema as object | undefined,\n }));\n }\n\n _metaToolMode = true;\n const { tools, elicitations } = await fetchGatewayTools(\n options?.limit,\n );\n\n // If the server returned embedded elicitations (partial result with\n // some servers needing OAuth), invoke the onIntegrationRequired callback\n // so the user can connect the missing integrations.\n if (elicitations?.length && config.onIntegrationRequired) {\n for (const e of elicitations) {\n if (e.url) {\n config.onIntegrationRequired(e.url, {\n id: e.integrationId ?? \"\",\n name: e.integrationName ?? e.message,\n });\n }\n }\n }\n\n return tools.map(toKontextTool);\n } catch (err) {\n const translated = translateError(err);\n if (translated instanceof AuthorizationRequiredError) {\n setState(\"needs_auth\");\n }\n throw translated;\n }\n },\n\n async execute(\n toolId: string,\n args?: Record<string, unknown>,\n ): Promise<ToolResult> {\n await ensureConnected();\n\n // Determine meta-tool mode if not yet known\n if (_metaToolMode === null) {\n const mcpTools = await mcp.listTools();\n _metaToolMode = hasMetaTools(mcpTools);\n }\n\n try {\n const result = _metaToolMode\n ? await mcp.callTool(\"EXECUTE_TOOL\", {\n tool_id: toolId,\n tool_arguments: args ?? {},\n })\n : await mcp.callTool(toolId, args);\n\n return { content: extractTextContent(result), raw: result };\n } catch (err) {\n const translated = translateError(err);\n if (translated instanceof AuthorizationRequiredError) {\n setState(\"needs_auth\");\n }\n throw translated;\n }\n },\n },\n\n on(\n event: \"stateChange\" | \"error\",\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n handler: (...args: any[]) => void,\n ): () => void {\n if (!_listeners.has(event)) {\n _listeners.set(event, new Set());\n }\n _listeners.get(event)!.add(handler);\n return () => {\n _listeners.get(event)?.delete(handler);\n };\n },\n\n get mcp() {\n return mcp;\n },\n };\n\n return client;\n}\n\n/**\n * Primary SDK client entrypoint.\n *\n * - `config.url` set: single-endpoint mode.\n * - `config.url` omitted: hybrid orchestrated mode.\n */\nexport function createKontextClient(\n config: KontextClientConfig & { url: string },\n): KontextClient;\nexport function createKontextClient(\n config: Omit<KontextClientConfig, \"url\"> & { url?: undefined },\n): KontextClient;\nexport function createKontextClient(\n config: KontextClientConfig,\n): KontextClient {\n if (config.url !== undefined) {\n if (typeof config.url !== \"string\" || config.url.trim().length === 0) {\n throw new ConfigError(\n \"url must be a non-empty string. Omit url for hybrid mode, or provide a full MCP endpoint URL.\",\n \"kontext_config_invalid_url\",\n );\n }\n return createSingleEndpointKontextClient(config);\n }\n\n return createKontextOrchestrator(config);\n}\n"]}
|