@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.
Files changed (63) hide show
  1. package/dist/adapters/ai/index.cjs +12 -2
  2. package/dist/adapters/ai/index.cjs.map +1 -1
  3. package/dist/adapters/ai/index.js +12 -2
  4. package/dist/adapters/ai/index.js.map +1 -1
  5. package/dist/adapters/cloudflare/index.cjs +13 -0
  6. package/dist/adapters/cloudflare/index.cjs.map +1 -1
  7. package/dist/adapters/cloudflare/index.js +13 -0
  8. package/dist/adapters/cloudflare/index.js.map +1 -1
  9. package/dist/adapters/cloudflare/react.cjs +12 -2
  10. package/dist/adapters/cloudflare/react.cjs.map +1 -1
  11. package/dist/adapters/cloudflare/react.js +12 -2
  12. package/dist/adapters/cloudflare/react.js.map +1 -1
  13. package/dist/adapters/react/index.cjs +12 -2
  14. package/dist/adapters/react/index.cjs.map +1 -1
  15. package/dist/adapters/react/index.js +12 -2
  16. package/dist/adapters/react/index.js.map +1 -1
  17. package/dist/client/index.cjs +108 -69
  18. package/dist/client/index.cjs.map +1 -1
  19. package/dist/client/index.d.cts +2 -0
  20. package/dist/client/index.d.ts +2 -0
  21. package/dist/client/index.js +109 -71
  22. package/dist/client/index.js.map +1 -1
  23. package/dist/errors.cjs +78 -0
  24. package/dist/errors.cjs.map +1 -1
  25. package/dist/errors.d.cts +7 -1
  26. package/dist/errors.d.ts +7 -1
  27. package/dist/errors.js +78 -1
  28. package/dist/errors.js.map +1 -1
  29. package/dist/index.cjs +151 -87
  30. package/dist/index.cjs.map +1 -1
  31. package/dist/index.d.cts +1 -1
  32. package/dist/index.d.ts +1 -1
  33. package/dist/index.js +152 -88
  34. package/dist/index.js.map +1 -1
  35. package/dist/{kontext-CgIBANFo.d.cts → kontext-CBPuE-hq.d.cts} +3 -0
  36. package/dist/{kontext-CgIBANFo.d.ts → kontext-CBPuE-hq.d.ts} +3 -0
  37. package/dist/management/index.cjs +15 -0
  38. package/dist/management/index.cjs.map +1 -1
  39. package/dist/management/index.d.cts +2 -2
  40. package/dist/management/index.d.ts +2 -2
  41. package/dist/management/index.js +15 -1
  42. package/dist/management/index.js.map +1 -1
  43. package/dist/mcp/index.cjs +32 -3
  44. package/dist/mcp/index.cjs.map +1 -1
  45. package/dist/mcp/index.d.cts +7 -1
  46. package/dist/mcp/index.d.ts +7 -1
  47. package/dist/mcp/index.js +33 -4
  48. package/dist/mcp/index.js.map +1 -1
  49. package/dist/oauth/index.cjs +12 -2
  50. package/dist/oauth/index.cjs.map +1 -1
  51. package/dist/oauth/index.d.cts +1 -1
  52. package/dist/oauth/index.d.ts +1 -1
  53. package/dist/oauth/index.js +12 -2
  54. package/dist/oauth/index.js.map +1 -1
  55. package/dist/server/index.cjs +55 -20
  56. package/dist/server/index.cjs.map +1 -1
  57. package/dist/server/index.d.cts +2 -2
  58. package/dist/server/index.d.ts +2 -2
  59. package/dist/server/index.js +56 -21
  60. package/dist/server/index.js.map +1 -1
  61. package/dist/{types-CzhnlJHW.d.cts → types-DicGI7ix.d.cts} +23 -1
  62. package/dist/{types-CzhnlJHW.d.ts → types-DicGI7ix.d.ts} +23 -1
  63. package/package.json +1 -1
package/dist/errors.cjs CHANGED
@@ -1,5 +1,7 @@
1
1
  'use strict';
2
2
 
3
+ var types_js = require('@modelcontextprotocol/sdk/types.js');
4
+
3
5
  // src/errors.ts
4
6
  var KontextError = class extends Error {
5
7
  /** Brand field for type narrowing without instanceof */
@@ -133,12 +135,20 @@ function isNetworkError(err) {
133
135
  if (typeof causeCode === "string" && NETWORK_ERROR_CODES.has(causeCode))
134
136
  return true;
135
137
  }
138
+ if (err.name === "TypeError") {
139
+ const msg = err.message.toLowerCase();
140
+ if (msg === "failed to fetch" || msg === "load failed" || msg.includes("networkerror")) {
141
+ return true;
142
+ }
143
+ }
136
144
  return false;
137
145
  }
138
146
  function isUnauthorizedError(err) {
139
147
  const props = errorProps(err);
140
148
  if (props.statusCode === 401 || props.status === 401) return true;
149
+ if (props.code === 401) return true;
141
150
  if (err.name === "UnauthorizedError") return true;
151
+ if (err.constructor?.name === "UnauthorizedError") return true;
142
152
  if (err.message === "Unauthorized") return true;
143
153
  return false;
144
154
  }
@@ -197,6 +207,73 @@ function parseHttpError(statusCode, body) {
197
207
  });
198
208
  }
199
209
  }
210
+ var MCP_CODE_MAP = {
211
+ [types_js.ErrorCode.ParseError]: { code: "kontext_mcp_parse_error" },
212
+ [types_js.ErrorCode.InvalidRequest]: { code: "kontext_mcp_invalid_request" },
213
+ [types_js.ErrorCode.MethodNotFound]: { code: "kontext_mcp_method_not_found" },
214
+ [types_js.ErrorCode.InvalidParams]: { code: "kontext_mcp_invalid_params" },
215
+ [types_js.ErrorCode.InternalError]: {
216
+ code: "kontext_mcp_internal_error",
217
+ statusCode: 500
218
+ },
219
+ [types_js.ErrorCode.RequestTimeout]: {
220
+ code: "kontext_mcp_session_expired",
221
+ statusCode: 401
222
+ },
223
+ [types_js.ErrorCode.ConnectionClosed]: { code: "kontext_mcp_session_error" }
224
+ };
225
+ function translateError(err) {
226
+ if (isKontextError(err)) return err;
227
+ if (!(err instanceof Error)) {
228
+ return new KontextError(String(err), "kontext_unknown_error");
229
+ }
230
+ const props = err;
231
+ if (props.code === types_js.ErrorCode.UrlElicitationRequired) {
232
+ const elicitations = props.elicitations ?? props.data?.elicitations;
233
+ const elicitation = elicitations?.[0];
234
+ return new IntegrationConnectionRequiredError(
235
+ elicitation?.integrationId ?? "unknown",
236
+ {
237
+ integrationName: elicitation?.integrationName,
238
+ connectUrl: elicitation?.url,
239
+ message: elicitation?.message,
240
+ cause: err
241
+ }
242
+ );
243
+ }
244
+ if (typeof props.code === "number" && props.code < 0) {
245
+ const entry = MCP_CODE_MAP[props.code];
246
+ if (entry) {
247
+ return new KontextError(err.message, entry.code, {
248
+ statusCode: entry.statusCode,
249
+ cause: err
250
+ });
251
+ }
252
+ return new KontextError(err.message, "kontext_mcp_error", {
253
+ cause: err,
254
+ meta: { mcpCode: props.code }
255
+ });
256
+ }
257
+ const statusCode = props.statusCode ?? props.status ?? (typeof props.code === "number" && props.code >= 400 && props.code < 600 ? props.code : void 0);
258
+ if (typeof statusCode === "number" && statusCode >= 400) {
259
+ if (statusCode === 401) {
260
+ return new AuthorizationRequiredError(err.message, { cause: err });
261
+ }
262
+ return new KontextError(err.message, "kontext_server_error", {
263
+ statusCode,
264
+ cause: err
265
+ });
266
+ }
267
+ if (isUnauthorizedError(err)) {
268
+ return new AuthorizationRequiredError(err.message, { cause: err });
269
+ }
270
+ if (isNetworkError(err)) {
271
+ return new NetworkError(err.message, { cause: err });
272
+ }
273
+ return new KontextError(err.message, "kontext_unknown_error", {
274
+ cause: err
275
+ });
276
+ }
200
277
 
201
278
  exports.AuthorizationRequiredError = AuthorizationRequiredError;
202
279
  exports.ConfigError = ConfigError;
@@ -209,5 +286,6 @@ exports.isKontextError = isKontextError;
209
286
  exports.isNetworkError = isNetworkError;
210
287
  exports.isUnauthorizedError = isUnauthorizedError;
211
288
  exports.parseHttpError = parseHttpError;
289
+ exports.translateError = translateError;
212
290
  //# sourceMappingURL=errors.cjs.map
213
291
  //# sourceMappingURL=errors.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts"],"names":[],"mappings":";;;AA8BO,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA;AAAA,EAE7B,YAAA,GAAe,IAAA;AAAA;AAAA,EAGf,IAAA;AAAA;AAAA,EAGA,UAAA;AAAA;AAAA,EAGA,OAAA;AAAA;AAAA,EAGA,SAAA;AAAA;AAAA,EAGA,IAAA;AAAA,EAET,WAAA,CACE,OAAA,EACA,IAAA,EACA,OAAA,EAMA;AACA,IAAA,KAAA,CAAM,OAAA,EAAS,EAAE,KAAA,EAAO,OAAA,EAAS,OAAO,CAAA;AACxC,IAAA,IAAA,CAAK,IAAA,GAAO,cAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA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AA,IAAQ,YAAA,IAAgB,IAAA,GACzD,MAAA,CAAQ,IAAA,CAAiC,UAAU,CAAA,GACnD,MAAA;AACN,MAAA,OAAO,IAAI,SAAA;AAAA,QACT,UAAA,GACI,CAAA,iCAAA,EAAoC,UAAU,CAAA,SAAA,CAAA,GAC9C,sCAAA;AAAA,QACJ,sBAAA;AAAA,QACA,EAAE,UAAA,EAAY,GAAA,EAAK,UAAA;AAAW,OAChC;AAAA,IACF;AAAA,IAEA;AACE,MAAA,IAAI,cAAc,GAAA,EAAK;AACrB,QAAA,OAAO,IAAI,SAAA;AAAA,UACT,CAAA,mBAAA,EAAsB,UAAU,CAAA,GAAA,EAAM,OAAO,CAAA,CAAA;AAAA,UAC7C,sBAAA;AAAA,UACA,EAAE,UAAA;AAAW,SACf;AAAA,MACF;AACA,MAAA,OAAO,IAAI,YAAA,CAAa,OAAA,EAAS,SAAA,IAAa,uBAAA,EAAyB;AAAA,QACrE;AAAA,OACD,CAAA;AAAA;AAEP","file":"errors.cjs","sourcesContent":["/**\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"]}
1
+ {"version":3,"sources":["../src/errors.ts"],"names":["ErrorCode"],"mappings":";;;;;AAgCO,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA;AAAA,EAE7B,YAAA,GAAe,IAAA;AAAA;AAAA,EAGf,IAAA;AAAA;AAAA,EAGA,UAAA;AAAA;AAAA,EAGA,OAAA;AAAA;AAAA,EAGA,SAAA;AAAA;AAAA,EAGA,IAAA;AAAA,EAET,WAAA,CACE,OAAA,EACA,IAAA,EACA,OAAA,EAMA;AACA,IAAA,KAAA,CAAM,OAAA,EAAS,EAAE,KAAA,EAAO,OAAA,EAAS,OAAO,CAAA;AACxC,IAAA,IAAA,CAAK,IAAA,GAAO,cAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,aAAa,OAAA,EAAS,UAAA;AAC3B,IAAA,IAAA,CAAK,YAAY,OAAA,EAAS,SAAA;AAC1B,IAAA,IAAA,CAAK,IAAA,GAAO,OAAA,EAAS,IAAA,IAAQ,EAAC;AAC9B,IAAA,IAAA,CAAK,OAAA,GAAU,mCAAmC,IAAI,CAAA,CAAA;AACtD,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,GAAA,CAAA,MAAA,CAAW,SAAS,CAAA;AAAA,EAClD;AAAA,EAEA,MAAA,GAAkC;A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AA,MACP,IAAA,EAAM,EAAE,OAAA,EAAS,KAAA,CAAM,IAAA;AAAK,KAC7B,CAAA;AAAA,EACH;AAKA,EAAA,MAAM,aAAc,KAAA,CAAM,UAAA,IACxB,KAAA,CAAM,MAAA,KACL,OAAO,KAAA,CAAM,IAAA,KAAS,QAAA,IAAY,KAAA,CAAM,QAAQ,GAAA,IAAO,KAAA,CAAM,IAAA,GAAO,GAAA,GACjE,MAAM,IAAA,GACN,MAAA,CAAA;AACN,EAAA,IAAI,OAAO,UAAA,KAAe,QAAA,IAAY,UAAA,IAAc,GAAA,EAAK;AACvD,IAAA,IAAI,eAAe,GAAA,EAAK;AACtB,MAAA,OAAO,IAAI,0BAAA,CAA2B,GAAA,CAAI,SAAS,EAAE,KAAA,EAAO,KAAK,CAAA;AAAA,IACnE;AACA,IAAA,OAAO,IAAI,YAAA,CAAa,GAAA,CAAI,OAAA,EAAS,sBAAA,EAAwB;AAAA,MAC3D,UAAA;AAAA,MACA,KAAA,EAAO;AAAA,KACR,CAAA;AAAA,EACH;AAGA,EAAA,IAAI,mBAAA,CAAoB,GAAG,CAAA,EAAG;AAC5B,IAAA,OAAO,IAAI,0BAAA,CAA2B,GAAA,CAAI,SAAS,EAAE,KAAA,EAAO,KAAK,CAAA;AAAA,EACnE;AAGA,EAAA,IAAI,cAAA,CAAe,GAAG,CAAA,EAAG;AACvB,IAAA,OAAO,IAAI,YAAA,CAAa,GAAA,CAAI,SAAS,EAAE,KAAA,EAAO,KAAK,CAAA;AAAA,EACrD;AAGA,EAAA,OAAO,IAAI,YAAA,CAAa,GAAA,CAAI,OAAA,EAAS,uBAAA,EAAyB;AAAA,IAC5D,KAAA,EAAO;AAAA,GACR,CAAA;AACH","file":"errors.cjs","sourcesContent":["/**\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"]}
package/dist/errors.d.cts CHANGED
@@ -157,5 +157,11 @@ interface ElicitationEntry {
157
157
  * Parse an HTTP response into an appropriate error.
158
158
  */
159
159
  declare function parseHttpError(statusCode: number, body?: unknown): KontextError;
160
+ /**
161
+ * Translate external errors into KontextError instances.
162
+ * Uses structural checks (numeric codes, status codes, system error codes)
163
+ * rather than fragile string matching.
164
+ */
165
+ declare function translateError(err: unknown): KontextError;
160
166
 
161
- export { AuthorizationRequiredError, ConfigError, type ElicitationEntry, HttpError, IntegrationConnectionRequiredError, KontextError, NetworkError, OAuthError, isKontextError, isNetworkError, isUnauthorizedError, parseHttpError };
167
+ export { AuthorizationRequiredError, ConfigError, type ElicitationEntry, HttpError, IntegrationConnectionRequiredError, KontextError, NetworkError, OAuthError, isKontextError, isNetworkError, isUnauthorizedError, parseHttpError, translateError };
package/dist/errors.d.ts CHANGED
@@ -157,5 +157,11 @@ interface ElicitationEntry {
157
157
  * Parse an HTTP response into an appropriate error.
158
158
  */
159
159
  declare function parseHttpError(statusCode: number, body?: unknown): KontextError;
160
+ /**
161
+ * Translate external errors into KontextError instances.
162
+ * Uses structural checks (numeric codes, status codes, system error codes)
163
+ * rather than fragile string matching.
164
+ */
165
+ declare function translateError(err: unknown): KontextError;
160
166
 
161
- export { AuthorizationRequiredError, ConfigError, type ElicitationEntry, HttpError, IntegrationConnectionRequiredError, KontextError, NetworkError, OAuthError, isKontextError, isNetworkError, isUnauthorizedError, parseHttpError };
167
+ export { AuthorizationRequiredError, ConfigError, type ElicitationEntry, HttpError, IntegrationConnectionRequiredError, KontextError, NetworkError, OAuthError, isKontextError, isNetworkError, isUnauthorizedError, parseHttpError, translateError };
package/dist/errors.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { ErrorCode } from '@modelcontextprotocol/sdk/types.js';
2
+
1
3
  // src/errors.ts
2
4
  var KontextError = class extends Error {
3
5
  /** Brand field for type narrowing without instanceof */
@@ -131,12 +133,20 @@ function isNetworkError(err) {
131
133
  if (typeof causeCode === "string" && NETWORK_ERROR_CODES.has(causeCode))
132
134
  return true;
133
135
  }
136
+ if (err.name === "TypeError") {
137
+ const msg = err.message.toLowerCase();
138
+ if (msg === "failed to fetch" || msg === "load failed" || msg.includes("networkerror")) {
139
+ return true;
140
+ }
141
+ }
134
142
  return false;
135
143
  }
136
144
  function isUnauthorizedError(err) {
137
145
  const props = errorProps(err);
138
146
  if (props.statusCode === 401 || props.status === 401) return true;
147
+ if (props.code === 401) return true;
139
148
  if (err.name === "UnauthorizedError") return true;
149
+ if (err.constructor?.name === "UnauthorizedError") return true;
140
150
  if (err.message === "Unauthorized") return true;
141
151
  return false;
142
152
  }
@@ -195,7 +205,74 @@ function parseHttpError(statusCode, body) {
195
205
  });
196
206
  }
197
207
  }
208
+ var MCP_CODE_MAP = {
209
+ [ErrorCode.ParseError]: { code: "kontext_mcp_parse_error" },
210
+ [ErrorCode.InvalidRequest]: { code: "kontext_mcp_invalid_request" },
211
+ [ErrorCode.MethodNotFound]: { code: "kontext_mcp_method_not_found" },
212
+ [ErrorCode.InvalidParams]: { code: "kontext_mcp_invalid_params" },
213
+ [ErrorCode.InternalError]: {
214
+ code: "kontext_mcp_internal_error",
215
+ statusCode: 500
216
+ },
217
+ [ErrorCode.RequestTimeout]: {
218
+ code: "kontext_mcp_session_expired",
219
+ statusCode: 401
220
+ },
221
+ [ErrorCode.ConnectionClosed]: { code: "kontext_mcp_session_error" }
222
+ };
223
+ function translateError(err) {
224
+ if (isKontextError(err)) return err;
225
+ if (!(err instanceof Error)) {
226
+ return new KontextError(String(err), "kontext_unknown_error");
227
+ }
228
+ const props = err;
229
+ if (props.code === ErrorCode.UrlElicitationRequired) {
230
+ const elicitations = props.elicitations ?? props.data?.elicitations;
231
+ const elicitation = elicitations?.[0];
232
+ return new IntegrationConnectionRequiredError(
233
+ elicitation?.integrationId ?? "unknown",
234
+ {
235
+ integrationName: elicitation?.integrationName,
236
+ connectUrl: elicitation?.url,
237
+ message: elicitation?.message,
238
+ cause: err
239
+ }
240
+ );
241
+ }
242
+ if (typeof props.code === "number" && props.code < 0) {
243
+ const entry = MCP_CODE_MAP[props.code];
244
+ if (entry) {
245
+ return new KontextError(err.message, entry.code, {
246
+ statusCode: entry.statusCode,
247
+ cause: err
248
+ });
249
+ }
250
+ return new KontextError(err.message, "kontext_mcp_error", {
251
+ cause: err,
252
+ meta: { mcpCode: props.code }
253
+ });
254
+ }
255
+ const statusCode = props.statusCode ?? props.status ?? (typeof props.code === "number" && props.code >= 400 && props.code < 600 ? props.code : void 0);
256
+ if (typeof statusCode === "number" && statusCode >= 400) {
257
+ if (statusCode === 401) {
258
+ return new AuthorizationRequiredError(err.message, { cause: err });
259
+ }
260
+ return new KontextError(err.message, "kontext_server_error", {
261
+ statusCode,
262
+ cause: err
263
+ });
264
+ }
265
+ if (isUnauthorizedError(err)) {
266
+ return new AuthorizationRequiredError(err.message, { cause: err });
267
+ }
268
+ if (isNetworkError(err)) {
269
+ return new NetworkError(err.message, { cause: err });
270
+ }
271
+ return new KontextError(err.message, "kontext_unknown_error", {
272
+ cause: err
273
+ });
274
+ }
198
275
 
199
- export { AuthorizationRequiredError, ConfigError, HttpError, IntegrationConnectionRequiredError, KontextError, NetworkError, OAuthError, isKontextError, isNetworkError, isUnauthorizedError, parseHttpError };
276
+ export { AuthorizationRequiredError, ConfigError, HttpError, IntegrationConnectionRequiredError, KontextError, NetworkError, OAuthError, isKontextError, isNetworkError, isUnauthorizedError, parseHttpError, translateError };
200
277
  //# sourceMappingURL=errors.js.map
201
278
  //# sourceMappingURL=errors.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts"],"names":[],"mappings":";AA8BO,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA;AAAA,EAE7B,YAAA,GAAe,IAAA;AAAA;AAAA,EAGf,IAAA;AAAA;AAAA,EAGA,UAAA;AAAA;AAAA,EAGA,OAAA;AAAA;AAAA,EAGA,SAAA;AAAA;AAAA,EAGA,IAAA;AAAA,EAET,WAAA,CACE,OAAA,EACA,IAAA,EACA,OAAA,EAMA;AACA,IAAA,KAAA,CAAM,OAAA,EAAS,EAAE,KAAA,EAAO,OAAA,EAAS,OAAO,CAAA;AACxC,IAAA,IAAA,CAAK,IAAA,GAAO,cAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,aAAa,OAAA,EAAS,UAAA;AAC3B,IAAA,IAAA,CAAK,YAAY,OAAA,EAAS,SAAA;AAC1B,IAAA,IAAA,CAAK,IAAA,GAAO,OAAA,EAAS,IAAA,IAAQ,EAAC;AAC9B,IAAA,IAAA,CAAK,OAAA,GAAU,mCAAmC,IAAI,CAAA,CAAA;AACtD,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,GAAA,CAAA,MAAA,CAAW,SAAS,CAAA;AAAA,EAClD;AAAA,EAEA,MAAA,GAAkC;AAChC,IAAA,OAAO;AAAA,MACL,MAAM,IAAA,CAAK,IAAA;AAAA,MACX,MAAM,IAAA,CAAK,IAAA;AAAA,MACX,SAAS,IAAA,CAAK,OAAA;AAAA,MACd,YAAY,IAAA,CAAK,UAAA;AAAA,MACjB,SAAS,IAAA,CAAK,OAAA;AAAA,MACd,WAAW,IAAA,CAAK,SAAA;AAAA,MAChB,IAAA,EAAM,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AAA,OACD,CAAA;AAAA;AAEP","file":"errors.js","sourcesContent":["/**\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"]}
1
+ {"version":3,"sources":["../src/errors.ts"],"names":[],"mappings":";;;AAgCO,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA;AAAA,EAE7B,YAAA,GAAe,IAAA;AAAA;AAAA,EAGf,IAAA;AAAA;AAAA,EAGA,UAAA;AAAA;AAA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,EAAO;AAAA,KACR,CAAA;AAAA,EACH;AAGA,EAAA,IAAI,mBAAA,CAAoB,GAAG,CAAA,EAAG;AAC5B,IAAA,OAAO,IAAI,0BAAA,CAA2B,GAAA,CAAI,SAAS,EAAE,KAAA,EAAO,KAAK,CAAA;AAAA,EACnE;AAGA,EAAA,IAAI,cAAA,CAAe,GAAG,CAAA,EAAG;AACvB,IAAA,OAAO,IAAI,YAAA,CAAa,GAAA,CAAI,SAAS,EAAE,KAAA,EAAO,KAAK,CAAA;AAAA,EACrD;AAGA,EAAA,OAAO,IAAI,YAAA,CAAa,GAAA,CAAI,OAAA,EAAS,uBAAA,EAAyB;AAAA,IAC5D,KAAA,EAAO;AAAA,GACR,CAAA;AACH","file":"errors.js","sourcesContent":["/**\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"]}