> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kontext.security/llms.txt
> Use this file to discover all available pages before exploring further.

# Errors

> Error handling patterns and reference for the Kontext SDK.

## KontextError base class

Errors thrown by the SDK's core operations are `KontextError` instances or subclasses. Each error carries structured metadata for programmatic handling.

```typescript theme={"system"}
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.security/errors/kontext_integration_connection_required"
    console.log(err.requestId);  // "req_abc123" (when available)
    console.log(err.meta);       // Additional contextual metadata
  }
}
```

### Properties

| Property     | Type                      | Description                                                                                        |
| ------------ | ------------------------- | -------------------------------------------------------------------------------------------------- |
| `code`       | `string`                  | Machine-readable error code, typically prefixed with `kontext_`. Upstream server codes may differ. |
| `statusCode` | `number?`                 | HTTP status code when applicable                                                                   |
| `docsUrl`    | `string`                  | Link to the error documentation page                                                               |
| `requestId`  | `string?`                 | Server request ID for debugging                                                                    |
| `meta`       | `Record<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.

```typescript theme={"system"}
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.

| Code                                      | Status | Meaning                                                                                                                                   |
| ----------------------------------------- | ------ | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `kontext_authorization_required`          | 401    | User needs to authenticate. Start the OAuth flow.                                                                                         |
| `kontext_integration_connection_required` | 403    | Integration needs user connection. Check `connectUrl` in meta or on the error instance. This can be OAuth or API key setup.               |
| `kontext_oauth_token_exchange_failed`     | 400    | OAuth token exchange failed. Inspect `errorCode` and `meta`.                                                                              |
| `kontext_oauth_code_verifier_missing`     | 400    | PKCE verifier is missing (usually callback state lost).                                                                                   |
| `kontext_config_missing_client_id`        | --     | SDK config is missing `clientId`.                                                                                                         |
| `kontext_config_missing_redirect_uri`     | --     | SDK config is missing `redirectUri`.                                                                                                      |
| `kontext_config_missing_auth_handler`     | --     | SDK config is missing `onAuthRequired`.                                                                                                   |
| `kontext_network_error`                   | --     | Connection or network failure. DNS resolution, timeouts, or refused connections.                                                          |
| `kontext_mcp_parse_error`                 | --     | The MCP peer returned invalid JSON-RPC payloads.                                                                                          |
| `kontext_mcp_invalid_request`             | --     | The MCP request was structurally invalid.                                                                                                 |
| `kontext_mcp_invalid_params`              | --     | Tool arguments or MCP call params were invalid.                                                                                           |
| `kontext_mcp_method_not_found`            | --     | The MCP peer does not support the requested method.                                                                                       |
| `kontext_mcp_internal_error`              | 500    | The MCP peer failed while handling the request.                                                                                           |
| `kontext_mcp_session_expired`             | 401    | The MCP session timed out or the transport considers it expired.                                                                          |
| `kontext_mcp_session_error`               | --     | The MCP transport closed unexpectedly.                                                                                                    |
| `kontext_mcp_error`                       | --     | Fallback for other negative MCP JSON-RPC codes.                                                                                           |
| `kontext_validation_error`                | 400    | Request validation failed. Check `validationErrors`.                                                                                      |
| `kontext_policy_denied`                   | 403    | Action denied by policy evaluation.                                                                                                       |
| `kontext_not_found`                       | 404    | Requested resource does not exist.                                                                                                        |
| `kontext_rate_limited`                    | 429    | Rate limit exceeded. Check `retryAfter` when available.                                                                                   |
| `kontext_server_error`                    | varies | Server 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`:

```typescript theme={"system"}
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.

```typescript theme={"system"}
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).

```typescript theme={"system"}
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.security/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.

```typescript theme={"system"}
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.

```typescript theme={"system"}
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.

```typescript theme={"system"}
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:

```typescript theme={"system"}
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.

```typescript theme={"system"}
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.
