> ## 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.

# Server Types

> Type reference for the Kontext server class, middleware options, and credential types.

## Kontext

```typescript theme={"system"}
import { Kontext } from "@kontext-dev/js-sdk/server";

const kontext = new Kontext({ clientId: "mcp_your-server" });
app.use(kontext.middleware(() => createServer()));
```

The `Kontext` class is the entry point for the server SDK. See [Server SDK](/server/overview) for the full usage guide.

## KontextOptions

Configuration for the `Kontext` constructor.

```typescript theme={"system"}
interface KontextOptions {
  clientId: string;
  apiUrl?: string;
  clientSecret?: string;
  tokenIssuer?: string | string[];
}
```

| Option         | Type                  | Default                          | Description                                   |
| -------------- | --------------------- | -------------------------------- | --------------------------------------------- |
| `clientId`     | `string`              | --                               | Your MCP server's OAuth client ID.            |
| `apiUrl`       | `string?`             | `"https://api.kontext.security"` | Kontext API base URL.                         |
| `clientSecret` | `string?`             | `KONTEXT_CLIENT_SECRET` env      | Client secret for server-side token exchange. |
| `tokenIssuer`  | `string \| string[]?` | `KONTEXT_TOKEN_ISSUER` env       | Expected token issuer(s) for verification.    |

## MiddlewareOptions

Options passed to `kontext.middleware()`.

```typescript theme={"system"}
interface MiddlewareOptions {
  mcpPath?: string;
  resourceServerUrl?: string;
  dangerouslyOmitAuth?: boolean;
  verifier?: OAuthTokenVerifier;
  metadataTransform?: (metadata: OAuthMetadata) => OAuthMetadata;
  onSessionInitialized?: (sessionId: string, authInfo?: AuthInfo, transport?: StreamableHTTPServerTransport) => void;
  onSessionClosed?: (sessionId: string) => void;
  bodyLimit?: string | number;
}
```

| Option                 | Type                                       | Default       | Description                                                      |
| ---------------------- | ------------------------------------------ | ------------- | ---------------------------------------------------------------- |
| `mcpPath`              | `string?`                                  | `"/mcp"`      | Path for the MCP transport endpoint.                             |
| `resourceServerUrl`    | `string?`                                  | Auto-detected | Public URL of your server. Required when behind a reverse proxy. |
| `dangerouslyOmitAuth`  | `boolean?`                                 | `false`       | Skip token verification. Development only.                       |
| `verifier`             | `OAuthTokenVerifier?`                      | Built-in JWKS | Custom token verification logic.                                 |
| `metadataTransform`    | `(metadata) => metadata`                   | --            | Rewrite OAuth metadata URLs for proxy/gateway setups.            |
| `onSessionInitialized` | `(sessionId, authInfo, transport) => void` | --            | Called when a new MCP session starts.                            |
| `onSessionClosed`      | `(sessionId) => void`                      | --            | Called when a session disconnects.                               |
| `bodyLimit`            | `string \| number?`                        | `"1mb"`       | Maximum request body size.                                       |

See [Middleware](/server/middleware) for detailed usage and examples.

## Methods

### kontext.require()

Exchange either a Kontext user access token or a known external end-user ID for an integration credential.

```typescript theme={"system"}
kontext.require(integration: string, token: string): Promise<IntegrationCredential>
kontext.require(integration: string, options: { userId: string }): Promise<IntegrationCredential>
```

Use the `token` overload when your MCP handler already has the authenticated user's Kontext access token.

Use the `{ userId }` overload when your confidential server has external-auth mappings configured and already knows the caller's external subject ID. This is the hard-cutover path for credential vault and shared `server_token` integrations.

Both overloads throw `IntegrationConnectionRequiredError` when the integration is not connected. In `{ userId }` mode, the error does not include a `connectUrl` because the SDK does not have a bearer token it can use to create a user-facing connect session. See [Credentials](/server/credentials).

### kontext.requireCredentials()

Resolve per-user credentials for internal integrations that use credential schemas instead of OAuth.

```typescript theme={"system"}
kontext.requireCredentials(integration: string, token: string): Promise<IntegrationResolvedCredentials>
```

### kontext.middleware()

Create an Express router with OAuth metadata, MCP transport, and authentication.

```typescript theme={"system"}
kontext.middleware(server: McpServer | (() => McpServer), options?: MiddlewareOptions): Router
```

Pass a factory function `() => McpServer` for concurrent session support. See [Middleware](/server/middleware).

### kontext.destroy()

Clean up sessions and resources. Call this on shutdown in serverless environments.

```typescript theme={"system"}
kontext.destroy(): Promise<void>
```

## IntegrationCredential

Returned by `kontext.require()`.

```typescript theme={"system"}
interface IntegrationCredential {
  accessToken: string;
  tokenType: string;
  authorization: string;
  expiresIn?: number;
  scope?: string;
  integration: string;
}
```

| Field           | Type      | Description                                                                        |
| --------------- | --------- | ---------------------------------------------------------------------------------- |
| `accessToken`   | `string`  | Raw access token for the integration.                                              |
| `tokenType`     | `string`  | Token type, typically `"Bearer"`.                                                  |
| `authorization` | `string`  | Pre-formatted header value (`"Bearer <token>"`). Pass directly to `Authorization`. |
| `expiresIn`     | `number?` | Seconds until the token expires.                                                   |
| `scope`         | `string?` | Scopes granted by the integration.                                                 |
| `integration`   | `string`  | Integration name this credential was issued for.                                   |

## IntegrationResolvedCredentials

Returned by `kontext.requireCredentials()`.

```typescript theme={"system"}
interface IntegrationResolvedCredentials {
  integration: string;
  integrationId: string;
  credentials: Record<string, string>;
}
```

The `credentials` map contains key-value pairs defined by the integration's credential schema.
