# How to Use the Kimi Code Node-SDK from MoonshotAI: Complete Integration Guide

> Integrate MoonshotAI Kimi Code into your Node.js apps using the official SDK. This guide covers seamless WebSocket/IPC RPC setup with KimiHarness and Session for powerful model interaction.

- Repository: [Moonshot AI/kimi-code](https://github.com/MoonshotAI/kimi-code)
- Tags: how-to-guide
- Published: 2026-08-14

---

**TL;DR:** The `@moonshot-ai/kimi-code-sdk` package is a TypeScript façade that lets Node applications create interactive sessions with a running Kimi Code server via WebSocket/IPC RPC, exposing a `KimiHarness` entry point and `Session` class for model interaction.

The Kimi Code Node-SDK provides a clean, type-safe interface for integrating MoonshotAI's coding assistant into your Node.js applications. Unlike standalone AI libraries, this SDK acts as a client to an existing Kimi Code server (the kap-server engine), handling all transport serialization, authentication, and session lifecycle management. This guide walks through installation, core architecture, and practical implementation patterns drawn directly from the MoonshotAI/kimi-code source.

## Installing and Setting Up the Node-SDK

Install the package from npm or your private registry:

```bash
npm install @moonshot-ai/kimi-code-sdk

```

The SDK requires TypeScript and a running Kimi Code server. By default, it connects to `localhost:6180`. For remote deployments, configure the server endpoint accordingly.

Import all public symbols from the package root in [`src/index.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/index.ts):

```typescript
import { createKimiHarness, Session, KimiAuthFacade } from '@moonshot-ai/kimi-code-sdk';

```

## Core Architecture of the Kimi Code Node-SDK

Understanding the SDK's component model helps you choose the right abstraction level for your use case.

### KimiHarness: The Entry Point

The **`KimiHarness`** class, implemented in [`src/kimi-harness.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/kimi-harness.ts), serves as the factory and lifecycle manager for all SDK operations. Created via `createKimiHarness()`, it handles:

- Configuration loading from the server's [`kimi.toml`](https://github.com/MoonshotAI/kimi-code/blob/main/kimi.toml)
- Model selection and resolution
- Session creation and pooling
- Clean shutdown via `harness.close()`

### Session: Interactive Model Interface

The **`Session`** class in [`src/session.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/session.ts) represents a single interactive conversation. All user-facing methods—`prompt()`, `steer()`, `runShellCommand()`—delegate to the server through an RPC client instance. Sessions are bound to a working directory and a specific model at creation time.

### RPC Transport Layer

Two low-level clients handle communication:

- **`SDKRpcClient`** ([`src/sdk-rpc-client.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/sdk-rpc-client.ts)): Legacy transport for v1 kap-server engines
- **`SDKRpcClientV2`** ([`src/sdk-rpc-client-v2.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/sdk-rpc-client-v2.ts)): Modern transport with capability detection and v2 engine features

The harness automatically selects the appropriate client based on server version detection.

### Supporting Components

- **`KimiAuthFacade`** ([`src/auth.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/auth.ts)): Wraps login, logout, and feedback upload RPCs
- **Catalog helpers** ([`src/catalog.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/catalog.ts)): Resolve model aliases and fetch the public model catalog

## Creating Your First Kimi Code Session

This minimal example from [`examples/kimi-harness-smoke.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/examples/kimi-harness-smoke.ts) demonstrates the complete lifecycle:

```typescript
// example-01-create-session.ts
import { createKimiHarness } from '@moonshot-ai/kimi-code-sdk';
import { mkdtemp, tmpdir } from 'node:fs/promises';
import { join } from 'node:path';
import { smokeIdentityFromEnv } from './runtime-smoke-helpers';

async function main() {
  const workDir = await mkdtemp(join(tmpdir(), 'kimi-work-'));
  const homeDir = await mkdtemp(join(tmpdir(), 'kimi-home-'));

  const harness = createKimiHarness({
    identity: smokeIdentityFromEnv(), // reads KIMI_TOKEN from env
    homeDir,
  });

  const config = await harness.getConfig();
  const model = config.defaultModel ?? 'kimi-code/kimi-for-coding';

  const session = await harness.createSession({ workDir, model });

  await session.prompt('Explain the purpose of the Kimi Code SDK.');

  await harness.close();
}

main().catch(err => {
  console.error(err);
  process.exit(1);
});

```

Key steps to remember:

1. Provide an **identity** (authentication token) and **home directory** to `createKimiHarness()`
2. Optionally fetch server configuration to discover default models
3. Create a **session** with working directory and model parameters
4. Always call **`harness.close()`** to release WebSocket/IPC connections

## Executing Shell Commands via Session

The `Session.runShellCommand()` method lets the model execute safe shell operations with captured output:

```typescript
// example-02-run-shell-command.ts
import { createKimiHarness } from '@moonshot-ai/kimi-code-sdk';
import { mkdtemp, tmpdir } from 'node:fs/promises';
import { join } from 'node:path';
import { smokeIdentityFromEnv } from './runtime-smoke-helpers';

async function main() {
  const workDir = await mkdtemp(join(tmpdir(), 'kimi-work-'));
  const harness = createKimiHarness({ 
    identity: smokeIdentityFromEnv(), 
    homeDir: workDir 
  });

  const session = await harness.createSession({ 
    workDir, 
    model: 'kimi-code/kimi-for-coding' 
  });

  const result = await session.runShellCommand('ls -la', { commandId: 'ls1' });
  console.log('STDOUT:', result.stdout);
  console.error('STDERR:', result.stderr);
  
  await harness.close();
}

main().catch(console.error);

```

The `commandId` parameter enables request tracking and idempotency—use unique identifiers for commands that may retry.

## Working with v2 Engine Capabilities

For servers running the `agent-core-v2` engine, access advanced features through capability detection:

```typescript
// example-03-list-and-use-capabilities (v2 only)
import { createKimiHarness } from '@moonshot-ai/kimi-code-sdk';
import { mkdtemp, tmpdir } from 'node:fs/promises';
import { join } from 'node:path';
import { smokeIdentityFromEnv } from './runtime-smoke-helpers';

async function main() {
  const workDir = await mkdtemp(join(tmpdir(), 'kimi-work-'));
  const harness = createKimiHarness({ 
    identity: smokeIdentityFromEnv(), 
    homeDir: workDir 
  });

  const session = await harness.createSession({ 
    workDir, 
    model: 'kimi-code/kimi-for-coding' 
  });

  try {
    const caps = await session.listCapabilities();
    console.log('Installed capabilities:', caps.map(c => c.id));
  } catch (e) {
    console.warn('Capability surface unavailable – you are probably on a v1 engine.');
  }

  await harness.close();
}

main().catch(console.error);

```

The **`capabilityRpc`** helper (used internally) validates v2 support before invoking capability methods, throwing clear errors for incompatible engines.

## Error Handling and Runtime Guarantees

The Kimi Code Node-SDK enforces several safety properties:

- **Request validation**: Empty strings and malformed payloads produce `KimiError` with `ErrorCodes.REQUEST_INVALID`
- **Session integrity**: `Session.close()` marks the session closed, fires `rpc.closeSession`, and removes all event listeners
- **Type safety**: All RPC payloads are declared in [`src/types.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/types.ts) and validated on both client and server boundaries

Catch SDK-specific errors by checking error codes:

```typescript
import { KimiError, ErrorCodes } from '@moonshot-ai/kimi-code-sdk';

try {
  await session.prompt('');
} catch (err) {
  if (err instanceof KimiError && err.code === ErrorCodes.REQUEST_INVALID) {
    console.error('Invalid request: empty prompt');
  }
}

```

## Authentication and Identity Management

For production deployments, implement proper identity sourcing. The `smokeIdentityFromEnv()` pattern reads `KIMI_TOKEN` from environment variables—adapt this to your secret management system (AWS Secrets Manager, HashiCorp Vault, etc.).

The `KimiAuthFacade` class in [`src/auth.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/auth.ts) wraps server-side authentication:

```typescript
import { KimiAuthFacade } from '@moonshot-ai/kimi-code-sdk';

const auth = new KimiAuthFacade(rpcClient);
await auth.login(token);
await auth.uploadFeedback(sessionId, feedbackData);
await auth.logout();

```

## Summary

- The **Kimi Code Node-SDK** (`@moonshot-ai/kimi-code-sdk`) requires a running kap-server and exposes high-level TypeScript abstractions for model interaction
- **Core workflow**: `createKimiHarness()` → `getConfig()` → `createSession()` → interact → `close()`
- **Key classes**: `KimiHarness` (factory/lifecycle), `Session` (interaction surface), `SDKRpcClient`/`SDKRpcClientV2` (transport)
- **Capability detection**: Use `listCapabilities()` and related methods only with v2 engines; handle gracefully for backward compatibility
- **Cleanup requirement**: Always invoke `harness.close()` to prevent WebSocket/IPC connection leaks

## Frequently Asked Questions

### What server does the Kimi Code Node-SDK connect to?

The SDK connects to a running Kimi Code kap-server engine, defaulting to `localhost:6180`. It does not bundle or start the server—you must deploy and run the server separately, then point the SDK at your endpoint.

### How do I choose between v1 and v2 RPC clients?

You don't choose manually. The `createKimiHarness()` function in [`src/kimi-harness.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/kimi-harness.ts) auto-detects the server version and instantiates `SDKRpcClient` or `SDKRpcClientV2` accordingly. For explicit v2-only features, use `createKimiHarnessV2()` which throws if the server lacks v2 support.

### What models can I use with the SDK?

Any model available in the server's catalog. Call `harness.getConfig()` to retrieve `defaultModel`, or use catalog helpers from [`src/catalog.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/catalog.ts) to list and resolve model aliases. The typical default is `kimi-code/kimi-for-coding`.

### How do I handle session persistence across process restarts?

Session state lives on the kap-server, not the SDK client. Save the `sessionId` returned by `harness.createSession()`, then implement a recovery mechanism that reconstructs a `Session` proxy pointing to the same server-side state. The SDK currently focuses on ephemeral sessions—long-lived persistence requires custom orchestration.