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

# Overview

> Typed TypeScript client for automating configuration in the Kontext identity control plane.

The `KontextManagementClient` is the typed management layer for the Kontext identity control plane. Use it to automate applications, integrations, service accounts, sessions, and traces in CI/CD pipelines, admin tooling, or internal automation.

## Install

```bash theme={"system"}
npm install @kontext-dev/js-sdk
```

## Initialize

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

const client = new KontextManagementClient({
  baseUrl: "https://api.kontext.security",
  credentials: {
    clientId: "sa_your-service-account",
    clientSecret: "your-secret",
  },
});
```

The client authenticates using OAuth client credentials. It fetches and caches an access token on the first request and refreshes it automatically when it expires.

## Constructor config

| Option        | Type                         | Default                        | Description                                                        |
| ------------- | ---------------------------- | ------------------------------ | ------------------------------------------------------------------ |
| `baseUrl`     | `string`                     | --                             | API base URL. Use `"https://api.kontext.security"` for production. |
| `credentials` | `{ clientId, clientSecret }` | --                             | Service account credentials from the dashboard.                    |
| `apiVersion`  | `string`                     | `"v1"`                         | API version prefix.                                                |
| `tokenUrl`    | `string`                     | `${baseUrl}/oauth2/token`      | OAuth token endpoint. Override for custom auth servers.            |
| `scopes`      | `string[]`                   | `["management:all"]`           | OAuth scopes to request.                                           |
| `audience`    | `string`                     | `${baseUrl}/api/${apiVersion}` | Token audience claim.                                              |

Create service account credentials in the Kontext dashboard under **Settings > Service Accounts**, or programmatically with `client.serviceAccounts.create()`.

Resource IDs used by the Management API are UUIDs. OAuth client IDs are separate (`app_<uuid>` for applications and `sa_<uuid>` for service accounts).

## Applications

Manage applications registered with your organization.

### List applications

```typescript theme={"system"}
const { items, nextCursor } = await client.applications.list({ limit: 10 });
```

### Get an application

```typescript theme={"system"}
const { application } = await client.applications.get(
  "550e8400-e29b-41d4-a716-446655440000",
);
```

### Create an application

```typescript theme={"system"}
const { application, oauth } = await client.applications.create({
  name: "My AI App",
  oauth: { redirectUris: ["http://localhost:3000/callback"] },
});

console.log(oauth.clientSecret); // Save this -- it is only shown once
```

### Update an application

```typescript theme={"system"}
const { application } = await client.applications.update(
  "550e8400-e29b-41d4-a716-446655440000",
  {
    name: "Renamed App",
  },
);
```

### Archive an application

```typescript theme={"system"}
await client.applications.archive("550e8400-e29b-41d4-a716-446655440000");
```

### Rotate client secret

```typescript theme={"system"}
const { oauth } = await client.applications.rotateSecret(
  "550e8400-e29b-41d4-a716-446655440000",
);
console.log(oauth.clientSecret); // Save this -- it is only shown once
```

Generates a new client secret and returns the full OAuth configuration. The previous secret is revoked immediately.

### OAuth configuration

```typescript theme={"system"}
const { oauth: oauthConfig } = await client.applications.getOAuth(
  "550e8400-e29b-41d4-a716-446655440000",
);

await client.applications.updateOAuth(
  "550e8400-e29b-41d4-a716-446655440000",
  {
    redirectUris: ["https://myapp.com/callback"],
  },
);
```

### Manage integrations

Attach or detach integrations from an application. An application can only use tools from its attached integrations.

```typescript theme={"system"}
// List attached integrations
const { integrationIds } = await client.applications.listIntegrations(
  "550e8400-e29b-41d4-a716-446655440000",
);

// Attach a single integration
await client.applications.attachIntegration(
  "550e8400-e29b-41d4-a716-446655440000",
  "11111111-1111-4111-8111-111111111111",
);

// Detach a single integration
await client.applications.detachIntegration(
  "550e8400-e29b-41d4-a716-446655440000",
  "11111111-1111-4111-8111-111111111111",
);

// Replace all integrations at once
await client.applications.setIntegrations(
  "550e8400-e29b-41d4-a716-446655440000",
  {
    integrationIds: [
      "11111111-1111-4111-8111-111111111111",
      "22222222-2222-4222-8222-222222222222",
    ],
  },
);
```

### Method reference

| Method                                    | Parameters                             | Returns                                                 |
| ----------------------------------------- | -------------------------------------- | ------------------------------------------------------- |
| `list(params?)`                           | `{ limit?, cursor? }`                  | `{ items: Application[], nextCursor? }`                 |
| `get(id)`                                 | `string`                               | `{ application: Application }`                          |
| `create(data)`                            | `CreateApplicationInput`               | `{ application: Application, oauth: ApplicationOAuth }` |
| `update(id, data)`                        | `string, UpdateApplicationInput`       | `{ application: Application }`                          |
| `archive(id)`                             | `string`                               | `void`                                                  |
| `rotateSecret(id)`                        | `string`                               | `{ oauth: ApplicationOAuth }`                           |
| `getOAuth(id)`                            | `string`                               | `{ oauth: ApplicationOAuth }`                           |
| `updateOAuth(id, data)`                   | `string, UpdateApplicationOAuthInput`  | `{ oauth: ApplicationOAuth }`                           |
| `listIntegrations(id)`                    | `string`                               | `{ integrationIds: string[] }`                          |
| `setIntegrations(id, data)`               | `string, { integrationIds: string[] }` | `{ integrationIds: string[] }`                          |
| `attachIntegration(appId, integrationId)` | `string, string`                       | `void`                                                  |
| `detachIntegration(appId, integrationId)` | `string, string`                       | `void`                                                  |
| `revokeAllAgentSessions(id)`              | `string`                               | `{ success: boolean, disconnectedCount: number }`       |

## Integrations

Manage integrations -- the external services your applications connect to.

### List integrations

```typescript theme={"system"}
const { items, nextCursor } = await client.integrations.list();
```

### Create an integration

```typescript theme={"system"}
const { integration } = await client.integrations.create({
  name: "GitHub",
  url: "https://github-mcp.example.com/mcp",
  authMode: "oauth",
});
```

### Validate an integration

```typescript theme={"system"}
const { status, message } = await client.integrations.validate(
  "11111111-1111-4111-8111-111111111111",
);
```

Tests the connection to the integration's MCP endpoint and returns the result. `status` is one of `"pending"`, `"valid"`, or `"invalid"`.

### Method reference

| Method             | Parameters                       | Returns                                                   |
| ------------------ | -------------------------------- | --------------------------------------------------------- |
| `list(params?)`    | `{ limit?, cursor? }`            | `{ items: Integration[], nextCursor? }`                   |
| `get(id)`          | `string`                         | `{ integration: Integration }`                            |
| `create(data)`     | `CreateIntegrationInput`         | `{ integration: Integration }`                            |
| `update(id, data)` | `string, UpdateIntegrationInput` | `{ integration: Integration }`                            |
| `archive(id)`      | `string`                         | `void`                                                    |
| `validate(id)`     | `string`                         | `{ status: "pending" \| "valid" \| "invalid", message? }` |

## Service accounts

Service accounts provide machine-to-machine credentials for the Management API. Each service account gets a `clientId` and `clientSecret` pair.

### Create a service account

```typescript theme={"system"}
const { serviceAccount, credentials } = await client.serviceAccounts.create({
  name: "CI Pipeline",
  description: "Used by GitHub Actions",
});

console.log(credentials.clientId);     // "sa_xxx"
console.log(credentials.clientSecret); // Save this -- shown once
```

### Rotate credentials

```typescript theme={"system"}
const { credentials } = await client.serviceAccounts.rotateSecret(
  "33333333-3333-4333-8333-333333333333",
);
```

The previous secret is revoked immediately.

### Revoke a service account

```typescript theme={"system"}
await client.serviceAccounts.revoke("33333333-3333-4333-8333-333333333333");
```

### Method reference

| Method             | Parameters               | Returns                                                       |
| ------------------ | ------------------------ | ------------------------------------------------------------- |
| `list(params?)`    | `{ limit?, cursor? }`    | `{ items: ServiceAccount[], nextCursor: string \| null }`     |
| `get(id)`          | `string`                 | `{ serviceAccount: ServiceAccount }`                          |
| `create(data)`     | `{ name, description? }` | `{ serviceAccount, credentials: { clientId, clientSecret } }` |
| `revoke(id)`       | `string`                 | `void`                                                        |
| `rotateSecret(id)` | `string`                 | `{ credentials: { clientId, clientSecret } }`                 |

## Sessions

View and manage active MCP sessions for your applications.

### List sessions

```typescript theme={"system"}
const { items } = await client.agentSessions.list(
  "550e8400-e29b-41d4-a716-446655440000",
  { limit: 20 },
);
```

### Get a session

```typescript theme={"system"}
const { session } = await client.agentSessions.get(
  "550e8400-e29b-41d4-a716-446655440000",
  "44444444-4444-4444-8444-444444444444",
);
```

### Revoke all sessions

```typescript theme={"system"}
const { success, disconnectedCount } = await client.agentSessions.revokeAll(
  "550e8400-e29b-41d4-a716-446655440000",
);
```

Terminates all active sessions for the application. Connected clients will need to re-authenticate.

### Method reference

| Method                          | Parameters                                      | Returns                                           |
| ------------------------------- | ----------------------------------------------- | ------------------------------------------------- |
| `list(applicationId, params?)`  | `string, { limit?, status?, includeInactive? }` | `{ items: AgentSession[] }`                       |
| `get(applicationId, sessionId)` | `string, string`                                | `{ session: AgentSession }`                       |
| `revokeAll(applicationId)`      | `string`                                        | `{ success: boolean, disconnectedCount: number }` |

## Traces

Query tool execution traces for observability and debugging.

### List traces

```typescript theme={"system"}
const { items } = await client.traces.list({
  userId: "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee",
  limit: 50,
});
```

Filter by `userId`, `sessionId`, or `agentId` to narrow results.

### Get a trace with events

```typescript theme={"system"}
const { trace, events } = await client.traces.get(
  "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
);
```

Returns the trace metadata and its full event timeline.

### Trace statistics

```typescript theme={"system"}
const { stats } = await client.traces.stats({ period: "7d" });
```

### Method reference

| Method                  | Parameters                                                                    | Returns                                  |
| ----------------------- | ----------------------------------------------------------------------------- | ---------------------------------------- |
| `list(params?)`         | `{ limit?, cursor?, offset?, userId?, sessionId?, agentId?, applicationId? }` | `{ items: Trace[], nextCursor? }`        |
| `get(traceId, params?)` | `string, { userId? }?`                                                        | `{ trace: Trace, events: TraceEvent[] }` |
| `stats(params?)`        | `{ period?, userId? }`                                                        | `{ stats: TraceStats }`                  |

## Events

Query trace events directly, without going through a specific trace.

```typescript theme={"system"}
const { items } = await client.events.list({ limit: 100 });
```

### Method reference

| Method          | Parameters   | Returns                 |
| --------------- | ------------ | ----------------------- |
| `list(params?)` | `{ limit? }` | `{ items: McpEvent[] }` |

## Token management

The client handles token lifecycle automatically. Two methods are available for manual control.

```typescript theme={"system"}
// Force a token refresh before the next request
await client.refreshToken();

// Clear the cached token (next request will fetch a new one)
client.clearToken();
```

Use `clearToken()` when rotating service account credentials -- the client picks up the new secret on the next request.

## Complete example

Create an application, set up an integration, and attach them together:

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

const client = new KontextManagementClient({
  baseUrl: "https://api.kontext.security",
  credentials: {
    clientId: "sa_your-service-account",
    clientSecret: "your-secret",
  },
});

// 1. Create the application
const { application, oauth } = await client.applications.create({
  name: "My AI App",
  oauth: { redirectUris: ["http://localhost:3000/callback"] },
});

console.log("App created:", application.id);
console.log("Client secret:", oauth.clientSecret);

// 2. Create an integration
const { integration } = await client.integrations.create({
  name: "GitHub",
  url: "https://github-mcp.example.com/mcp",
  authMode: "oauth",
});

console.log("Integration created:", integration.id);

// 3. Attach the integration to the application
await client.applications.attachIntegration(application.id, integration.id);

// 4. Verify the setup
const { integrationIds } = await client.applications.listIntegrations(application.id);
console.log("Attached integrations:", integrationIds);
```

## Error handling

The management client throws the same error types as the rest of the SDK. See [Errors](/errors) for the full reference.

```typescript theme={"system"}
import { HttpError, isKontextError } from "@kontext-dev/js-sdk/errors";

try {
  await client.applications.get("00000000-0000-4000-8000-000000000000");
} catch (err) {
  if (err instanceof HttpError) {
    console.log(err.statusCode);       // 404
    console.log(err.message);          // "Application not found"
  }
}
```

Common cases:

* **401** -- Invalid or expired service account credentials. Check your `clientId` and `clientSecret`.
* **403** -- Insufficient permissions. The service account may need additional scopes.
* **404** -- Resource not found. Verify the ID.
* **429** -- Rate limit exceeded. The error includes a `retryAfter` value in seconds.

## Next steps

* [TypeScript SDK](/sdks/typescript) -- Overview of all SDK entry points and subpath exports.
* [Errors](/errors) -- Full error hierarchy, error codes, and handling patterns.
