Skip to main content

KontextError base class

Errors thrown by the SDK’s core operations are KontextError instances or subclasses. Each error carries structured metadata for programmatic handling.
import { isKontextError } from "@kontext-dev/js-sdk/errors";

try {
  await client.tools.execute("github:list_repos", { query: "mcp" });
} catch (err) {
  if (isKontextError(err)) {
    console.log(err.code);       // "kontext_integration_connection_required"
    console.log(err.statusCode); // 403
    console.log(err.docsUrl);    // "https://docs.kontext.dev/errors/kontext_integration_connection_required"
    console.log(err.requestId);  // "req_abc123" (when available)
    console.log(err.meta);       // Additional contextual metadata
  }
}

Properties

PropertyTypeDescription
codestringMachine-readable error code, typically prefixed with kontext_. Upstream server codes may differ.
statusCodenumber?HTTP status code when applicable
docsUrlstringLink to the error documentation page
requestIdstring?Server request ID for debugging
metaRecord<string, unknown>Contextual metadata (integration IDs, URLs, etc.)

Type guard

Use isKontextError() to check errors without instanceof. This works across package versions and bundler deduplication.
import { isKontextError } from "@kontext-dev/js-sdk/errors";

if (isKontextError(err)) {
  // err is typed as KontextError
}

Error codes

The SDK emits many kontext_* codes. The table below lists common codes you should handle explicitly.
CodeStatusMeaning
kontext_authorization_required401User needs to authenticate. Start the OAuth flow.
kontext_integration_connection_required403Integration needs user connection. Check connectUrl in meta or on the error instance. This can be OAuth or API key setup.
kontext_oauth_token_exchange_failed400OAuth token exchange failed. Inspect errorCode and meta.
kontext_oauth_code_verifier_missing400PKCE verifier is missing (usually callback state lost).
kontext_config_missing_client_idSDK config is missing clientId.
kontext_config_missing_redirect_uriSDK config is missing redirectUri.
kontext_config_missing_auth_handlerSDK config is missing onAuthRequired.
kontext_network_errorConnection or network failure. DNS resolution, timeouts, or refused connections.
kontext_mcp_parse_errorThe MCP peer returned invalid JSON-RPC payloads.
kontext_mcp_invalid_requestThe MCP request was structurally invalid.
kontext_mcp_invalid_paramsTool arguments or MCP call params were invalid.
kontext_mcp_method_not_foundThe MCP peer does not support the requested method.
kontext_mcp_internal_error500The MCP peer failed while handling the request.
kontext_mcp_session_expired401The MCP session timed out or the transport considers it expired.
kontext_mcp_session_errorThe MCP transport closed unexpectedly.
kontext_mcp_errorFallback for other negative MCP JSON-RPC codes.
kontext_validation_error400Request validation failed. Check validationErrors.
kontext_policy_denied403Action denied by policy evaluation.
kontext_not_found404Requested resource does not exist.
kontext_rate_limited429Rate limit exceeded. Check retryAfter when available.
kontext_server_errorvariesServer or upstream failure. Commonly 5xx, but the client translation layer may emit this for other HTTP status codes. Retry with backoff.

Specific error classes

Import error classes from @kontext-dev/js-sdk/errors:
import {
  KontextError,
  AuthorizationRequiredError,
  IntegrationConnectionRequiredError,
  OAuthError,
  ConfigError,
  NetworkError,
  HttpError,
  translateError,
  isKontextError,
  isNetworkError,
  isUnauthorizedError,
} from "@kontext-dev/js-sdk/errors";

AuthorizationRequiredError

Thrown when no valid credentials are available. Redirect the user to sign in.
import { AuthorizationRequiredError } from "@kontext-dev/js-sdk/errors";

try {
  await client.connect();
} catch (err) {
  if (err instanceof AuthorizationRequiredError) {
    // err.authorizationUrl may contain the OAuth URL
    redirectToLogin();
  }
}

IntegrationConnectionRequiredError

Thrown when a user has not connected a required integration. The connectUrl property may contain the URL to complete integration setup (OAuth or API key flow).
import { IntegrationConnectionRequiredError } from "@kontext-dev/js-sdk/errors";

try {
  const github = await kontext.require("github", token);
} catch (err) {
  if (err instanceof IntegrationConnectionRequiredError) {
    console.log(err.integrationId);   // "github"
    console.log(err.integrationName); // "GitHub"
    console.log(err.connectUrl);      // "https://app.kontext.dev/oauth/connect?session=..."
    // Open connectUrl so the user can complete required connection steps
  }
}
If you called kontext.require("github", { userId }), connectUrl is usually undefined. That path does not have a bearer token available to create a connect session on the user’s behalf.

OAuthError

Thrown when an OAuth flow fails. Covers state validation errors, token exchange failures, and provider-side rejections.
import { OAuthError } from "@kontext-dev/js-sdk/errors";

try {
  await client.auth.handleCallback(callbackUrl);
} catch (err) {
  if (err instanceof OAuthError) {
    console.log(err.errorCode);        // Provider error code
    console.log(err.errorDescription); // Human-readable description
  }
}

ConfigError

Thrown at initialization when the SDK is misconfigured. These are deterministic errors you can catch during startup.
import { createKontextClient } from "@kontext-dev/js-sdk/client";
import { ConfigError } from "@kontext-dev/js-sdk/errors";

try {
  createKontextClient({
    clientId: "",
    redirectUri: "http://localhost:3000/callback",
    onAuthRequired: () => {},
  });
} catch (err) {
  if (err instanceof ConfigError) {
    // Fix your configuration
    console.log(err.message); // "clientId is required..."
  }
}

NetworkError

Thrown on connection failures — DNS resolution errors, timeouts, refused connections.

HttpError

Thrown when the server returns an HTTP error. Includes extra fields for specific status codes.
import { HttpError } from "@kontext-dev/js-sdk/errors";

try {
  await client.applications.create({ name: "" });
} catch (err) {
  if (err instanceof HttpError) {
    console.log(err.statusCode);        // 400, 429, etc.
    console.log(err.retryAfter);        // Seconds to wait (on 429)
    console.log(err.validationErrors);  // [{ field: "name", message: "required" }]
  }
}

Detection helpers

Two utility functions for common checks:
import { isNetworkError, isUnauthorizedError } from "@kontext-dev/js-sdk/errors";

// Check for network-level failures (timeouts, DNS, refused connections)
if (err instanceof Error && isNetworkError(err)) {
  showRetryPrompt();
}

// Check for 401 / unauthorized responses
if (err instanceof Error && isUnauthorizedError(err)) {
  redirectToLogin();
}
These helpers primarily use structural checks (status codes, system error codes) with fallback string checks for compatibility with the MCP SDK, so they work with errors from any source — the SDK, fetch wrappers, or the MCP protocol.

Error translation helper

Use translateError() when you are working with low-level MCP client calls or third-party wrappers and want the same normalized KontextError surface that the higher-level SDK uses internally.
import { translateError } from "@kontext-dev/js-sdk/errors";

try {
  await mcp.callTool("search", {});
} catch (err) {
  const normalized = translateError(err);
  console.log(normalized.code, normalized.statusCode);
}
translateError() maps MCP JSON-RPC negative codes, Streamable HTTP errors, 401s, and browser/network failures into stable kontext_* codes.