How to Set Up the Kimi Code Server with REST and WebSocket Endpoints

To set up the Kimi Code server, bootstrap the DI scope in packages/kap-server/src/start.ts, register Fastify routes for /api/v1/* (REST) and /ws/v1/* (WebSocket), configure the bearer token authentication service, and start the listener with automatic port retry logic.

The Kimi Code server (kap-server) from the MoonshotAI/kimi-code repository is a Fastify-based runtime built on the @moonshot-ai/agent-core-v2 DI engine. It exposes comprehensive REST and WebSocket endpoints for session management, transcript streaming, and model catalog operations, making it deployable as a standalone service or embeddable within custom CLI tools and IDE extensions.

Bootstrap Architecture and Server Initialization

The server initialization follows a strict bootstrap sequence defined in packages/kap-server/src/start.ts. When startServer() executes, it first resolves the core DI scope to instantiate essential services including logging, configuration, workspace management, the model catalog, and the transcript engine.

Following scope initialization, the server creates a Fastify instance and registers three distinct route groups:

  • REST API (/api/v1/*) — registered via registerApiV1Routes
  • WebSocket API (/ws/v1/*) — registered via registerWsV1
  • Static web assets — optionally registered via registerWebAssetRoutes when serving the React-based UI

This registration occurs at lines 30–34 of the startup file, cleanly separating transport concerns from core business logic.

Configuring the REST API Endpoints

The REST interface declared in packages/kap-server/src/routes/registerApiV1Routes.ts exposes stateless HTTP endpoints for session lifecycle management, transcript paging, and model catalog queries. These routes interact with the TranscriptService (handling op-batch sequencing and live streaming) and the ModelCatalogRefreshScheduler for real-time model availability.

Default binding follows the constants defined at lines 39–41 of start.ts:

  • Host: 127.0.0.1
  • Port: 58627

The server implements aggressive port conflict resolution, retrying the binding operation up to 100 times if the requested port is in use (see the listen loop at lines 548–577).

Setting Up WebSocket Infrastructure

The WebSocket layer, registered in packages/kap-server/src/transport/ws/v1/registerWsV1.ts, provides low-latency push capabilities for live transcript operations and file-system events. During initialization (lines 44–52 of start.ts), the server wires three critical components:

  • ConnectionRegistry — tracks active socket connections and metadata
  • SessionEventBroadcaster — pushes session-wide events such as event.session.work_changed to subscribed clients
  • FsWatchBridge — mirrors file-system changes into the transcript stream in real-time

Clients connect to ws://<host>:<port>/ws/v1 (or wss:// when TLS is configured), with the @moonshot-ai/klient library handling the authentication handshake automatically.

Authentication and Security Configuration

The server enforces unified authentication across both REST and WebSocket transports via the AuthTokenService defined in packages/kap-server/src/services/auth/authTokenService.ts. A persistent bearer token (stored by default in ~/.kimi-code/server/token-store.json) protects every HTTP route and WebSocket upgrade.

Security requirements include:

  • TLS enforcement — The server refuses non-loopback bindings without TLS termination (lines 64–68), throwing a fatal error if you attempt to bind to 0.0.0.0 without a reverse proxy or certificates
  • Optional secondary credential — An rpcToken can be configured as a second credential that applies only to RPC surfaces (lines 96–98)
  • Debug endpoints — Pass --debug-endpoints to expose /debug/* REST and WebSocket routes; these are automatically restricted to loopback interfaces for safety (lines 71–73)

Development Server Setup

To run a local development instance with hot-reloading and debug capabilities:


# Clone and install dependencies

git clone https://github.com/MoonshotAI/kimi-code.git
cd kimi-code
pnpm install

# Build the workspace

pnpm build

# Start the server on loopback (TLS not required for localhost)

pnpm exec node -r ts-node/register packages/kap-server/src/start.ts \
  --host 127.0.0.1 \
  --port 58627 \
  --debug-endpoints \
  --insecure-no-tls

The startServer function supports several configuration overrides:

  • --home-dir <path> — overrides the default ~/.kimi-code workspace directory (also configurable via KIMI_HOME environment variable)
  • --web-assets-dir <path> — serves the React UI from apps/kimi-web/dist at the root path (GET /)
  • --host and --port — customize the listening address

Upon first startup, the server generates a one-time token printed to stdout:

🗝️  Token: a5f2c9e1-…-c4d3

Connecting Clients to REST and WebSocket Endpoints

Once the server is listening, integrate the official client library or use raw HTTP/WebSocket connections:

import { createKlient } from '@moonshot-ai/klient';

const client = createKlient({
  baseUrl: 'http://127.0.0.1:58627',
  auth: { bearer: 'a5f2c9e1-…-c4d3' },
});

// REST call example
const meta = await client.get('/api/v1/meta');

// WebSocket connection
const ws = client.ws('/ws/v1');
ws.on('open', () => console.log('WebSocket ready for session events'));

The createKlient constructor automatically manages the bearer token injection for both HTTP headers and the WebSocket handshake protocol.

Summary

  • Bootstrap sequence — The server initializes the DI scope in packages/kap-server/src/start.ts, resolving core services before creating the Fastify instance
  • Dual transport — REST endpoints live under /api/v1/* while WebSocket connections use /ws/v1/*, both sharing the same authentication context
  • Security defaults — TLS is mandatory for public interfaces; use --insecure-no-tls only for local loopback development
  • Port handling — Automatic retry logic attempts up to 100 ports if the default 58627 is occupied
  • Client integration — Use @moonshot-ai/klient with the generated bearer token to connect to both REST and WebSocket surfaces

Frequently Asked Questions

What is the default host and port for the Kimi Code server?

The server defaults to binding on 127.0.0.1:58627 as defined by the constants in packages/kap-server/src/start.ts at lines 39–41. You can override these using the --host and --port CLI flags or by setting the corresponding options in ServerStartOptions.

How does WebSocket authentication work?

WebSocket connections use the same bearer token as REST endpoints. The registerWsV1 function in packages/kap-server/src/transport/ws/v1/registerWsV1.ts validates the token during the upgrade handshake before establishing the socket connection, ensuring unified security across both transport layers.

Can I run the server without TLS for local development?

Yes, but only when binding to loopback addresses (127.0.0.1 or localhost). Pass the --insecure-no-tls flag to bypass TLS requirements. The server explicitly blocks non-loopback bindings without TLS at lines 64–68 of start.ts to prevent accidental insecure deployments.

How do I enable the debug REST and WebSocket endpoints?

Start the server with the --debug-endpoints flag. This exposes additional routes under /debug/* for both HTTP and WebSocket transports. For security, these endpoints are automatically disabled when the server binds to public interfaces; they only function on loopback addresses.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →