npm package: @kapy.dev/sdk
Description: Official TypeScript client for the [Kapy](https://kapy.dev) engine. Use it in any Node.js or edge runtime to create research plans, execute them against your data, and retrieve results.
Latest version: 1.5.0

# @kapy.dev/sdk

Official TypeScript client for the [Kapy](https://kapy.dev) engine. Use it in any Node.js or edge runtime to create research plans, execute them against your data, and retrieve results.

## Installation

```bash
npm install @kapy.dev/sdk
# or
pnpm add @kapy.dev/sdk
```

## Quick start

```ts
import { createClient } from "@kapy.dev/sdk";

const client = createClient({ apiKey: "your_api_key" });

// List existing plans
const plans = await client.getPlans();

// Create a new research plan
const { plan_id } = await client.createPlan({
  question: "What are the top drivers of user retention?",
  kind: "auto",
  context: "",
});

// Execute it
const { execution_id } = await client.executePlan(plan_id, { input: {} });

// Poll until done
const result = await client.getExecution(plan_id, execution_id);
console.log(result.status, result.output);
```

The API key can also be set via the `KAPY_API_KEY` environment variable — no config argument needed in that case.

## Client API

### `createClient(config?)`

Returns a `KapyClient` instance.

| Option    | Type     | Default                             | Description                      |
|-----------|----------|-------------------------------------|----------------------------------|
| `apiKey`  | `string` | `process.env.KAPY_API_KEY`          | Bearer token for authentication  |
| `baseUrl` | `string` | `https://engine.kapy.dev/v1`        | Override the engine base URL     |

### Methods

#### Plans

| Method | Description |
|--------|-------------|
| `getPlans(userId?)` | List all research plans. Optional `userId` filter. |
| `createPlan(body)` | Create a new research plan and enqueue it for processing. |
| `getPlan(id)` | Get plan details and output schema (once ready). |
| `deletePlan(id)` | Delete a plan and all its executions. |

#### Executions

| Method | Description |
|--------|-------------|
| `executePlan(id, body)` | Run an existing plan against an input object. |
| `getExecution(id, executionId)` | Fetch execution result. Status is `pending` while running. |
| `deleteExecution(id, executionId)` | Delete a single execution. |
| `planAndExecute(body)` | Atomically create a plan and reserve an execution slot. |

## Bridge — frontend proxy

If you're building a web app, you don't want to expose your API key to the browser. The SDK provides `createBridge` to proxy the safe subset of the API through your own backend endpoint.

### Setup (Express example)

```ts
import express from "express";
import { createClient, createBridge } from "@kapy.dev/sdk";

const client = createClient(); // reads KAPY_API_KEY from env

const bridge = createBridge({
  client,

  // Optional: disable specific actions
  disabled: [], // e.g. ["planAndExecute"]

  // Optional: inject server-side context per request
  getContext: async (req) => ({
    userId: req.user?.id,          // injected into API calls that accept userId
    inputOverride: {               // merged into `input` of any POST body
      tenantId: req.user?.tenantId,
    },
  }),
});

const app = express();
app.use(express.json());

// Single endpoint that multiplexes all allowed actions
app.post("/krl", bridge.express);
```

For non-Express frameworks, use `bridge.handle(body, req)` directly:

```ts
// Next.js App Router example
export async function POST(request: Request) {
  const body = await request.json();
  const result = await bridge.handle(body, request);
  return Response.json(result.body, { status: result.status });
}
```

### Bridge protocol

The bridge accepts a single `POST` request with a JSON body:

```json
{
  "action": "getPlans" | "executePlan" | "getExecution" | "planAndExecute",
  "planId": 123,
  "executionId": 456,
  "input": {},
  "question": "..."
}
```

Response:

```json
{ "data": { ... } }
// or on error:
{ "error": "message" }
```

### Allowed actions

| Action | Required fields | Description |
|--------|----------------|-------------|
| `getPlans` | — | List plans |
| `executePlan` | `planId`, `input` | Execute an existing plan |
| `getExecution` | `planId`, `executionId` | Fetch execution result |
| `planAndExecute` | `question`, `input` | Create plan + execute |

No other API endpoints are accessible through the bridge.

## TypeScript

All methods are fully typed. Import the types you need:

```ts
import type {
  PlanSummary,
  Plan,
  Execution,
  ExecutionStatus,
  PlanKind,
} from "@kapy.dev/sdk";
```

## License

MIT