What Is the kap-server Package in MoonshotAI/kimi-code? Architecture and API Guide
The kap-server package is the core Fastify-based backend that exposes Kimi Code's DI × Scope agent engine through REST and WebSocket endpoints, handling sessions, workspaces, transcript streaming, and global search.
The kap-server package serves as the bridge between MoonshotAI's agent-core-v2 engine and client-facing APIs. Located at packages/kap-server in the kimi-code repository, it transforms the core agent capabilities into a network-accessible service used by the CLI, TUI, and web interfaces.
Core Architecture of kap-server
The package follows a layered design that separates transport concerns from business logic. All services are resolved from a single App-level DI scope created during bootstrap.
Bootstrap and Dependency Injection
In src/start.ts, the bootstrap() function initializes the application scope and wires core services:
- Scope creation: Establishes the root container for
@moonshot-ai/agent-core-v2services - Fastify registration: Mounts route handlers and middleware
- Lifecycle management: Provides graceful shutdown hooks
This design ensures that session, workspace, and transcript services share a consistent dependency graph throughout the server lifetime.
Transport Layer: HTTP and WebSocket
The transport layer in src/transport/dispatcher.ts routes incoming requests across three surfaces:
| Surface | Purpose | Protocol Version |
|---|---|---|
| REST API | CRUD operations, search, file access | V1 and V2 |
| WebSocket V1 | Bidirectional streaming, real-time transcripts | V1 |
| Debug RPC | Introspection and service invocation | V1 (opt-in) |
Both API versions wrap responses in a standardized envelope: { code, msg, data, request_id }. The code field encodes business outcomes (e.g., 40001 for invalid parameters), while HTTP status codes indicate transport failures only.
WebSocket V1 Protocol Implementation
The src/transport/ws/v1/wsConnectionV1.ts module implements a custom bidirectional protocol for CLI/TUI clients. Key features include:
- Connection registry: Tracks active clients with bearer token identity
- Event broadcasting: Global events reach all connections; session-specific events filter by
agent_filter - Transcript-grade filtering: Fine-grained control over which ops each client receives
Clients subscribe to sessions using a filter array that limits the agent roles they observe:
ws.send(JSON.stringify({
type: 'subscribe_v2',
session_id: 'sess_12345',
agent_filter: ['assistant'], // Only receive assistant messages
}));
Session and Workspace Services
Session management lives in src/routes/sessions.ts and its backing services. The core abstractions include:
ISessionIndex: Tracks session metadata and lifecycle stateIWorkspaceService: Mediates file-system access within workspace boundaries- Transcript service: Provides op-batch sequencing for streaming turn data
The transcript implementation in src/services/transcript/transcriptService.ts guarantees ordered delivery of operations across both REST polling and WebSocket push modes.
Global Search Architecture
The search system in src/search/searchService.ts provides cross-session full-text retrieval:
- Storage: Embedded
MiniDbindex at<home>/search-index - Execution modes: Inline (main thread) or worker thread via
KIMI_CODE_EXPERIMENTAL_SEARCH_WORKER - Query budgeting: Term limits, posting caps, and timeouts prevent resource exhaustion
- Pagination tokens: Encode index generation for consistency across rebuilds
Security and Observability
The middleware stack in src/middleware/auth.ts implements defense in depth:
- Host-check validation for loopback/production binds
- CORS policy enforcement
- Security header injection
- Bearer token authentication
- Rate limiting per connection identity
Optional cloud telemetry in src/services/telemetry.ts records engine events when explicitly enabled.
Running kap-server Programmatically
Import the package to embed the server in your own application:
import { startServer, ServerStartOptions } from '@moonshot-ai/kap-server';
const opts: ServerStartOptions = {
host: '127.0.0.1',
port: 58627,
hostIdentity: {
product_name: 'my-app',
version: '1.0.0',
platform: 'node',
},
debugEndpoints: true, // Enable /api/v1/debug/* for inspection
};
startServer(opts).then(({ app, close }) => {
console.log(`KAP server listening on http://${opts.host}:${opts.port}`);
process.on('SIGINT', async () => {
await close();
process.exit(0);
});
});
Using the REST API
Creating a Session
curl -X POST http://localhost:58627/api/v1/sessions \
-H "Authorization: Bearer $KIMI_TOKEN" \
-H "Content-Type: application/json" \
-d '{"workspace_id":"default"}'
Response envelope:
{
"code": 0,
"msg": "OK",
"data": {
"session_id": "sess_12345",
"workspace_id": "default"
},
"request_id": "req_abcde"
}
Executing a Global Search
curl -X POST http://localhost:58627/api/v1/search \
-H "Authorization: Bearer $KIMI_TOKEN" \
-H "Content-Type: application/json" \
-d '{"query":"debugging", "mode":"terms"}'
Debug RPC Surface
When started with --debug-endpoints on a loopback interface, kap-server exposes /api/v1/debug/* routes. These allow reflection-based invocation of any registered DI service, powering the kimi-inspect diagnostic UI.
Warning: Never enable debug endpoints on production binds or exposed interfaces.
Summary
- kap-server is the Fastify-based backend package that exposes Kimi Code's agent engine via REST and WebSocket
- All services resolve from a single App-scope DI container created in
src/start.ts - The V1 WebSocket protocol in
wsConnectionV1.tssupports filtered, bidirectional transcript streaming - Global search uses
MiniDbwith optional worker-thread execution controlled byKIMI_CODE_EXPERIMENTAL_SEARCH_WORKER - Responses use a standardized envelope separating business codes from HTTP transport status
- Debug endpoints provide deep introspection when enabled on loopback interfaces
Frequently Asked Questions
What is the relationship between kap-server and agent-core-v2?
kap-server depends on @moonshot-ai/agent-core-v2 and wraps its DI × Scope engine in network endpoints. The core provides session management, agent execution, and transcript generation; kap-server adds HTTP routing, authentication, and client protocol adaptation.
Can I run kap-server without the rest of kimi-code?
Yes. The package exports startServer() for programmatic embedding and includes a CLI entry point. You need only configure hostIdentity and provide a valid bearer token mechanism. The plugin marketplace and telemetry features are optional.
How does transcript streaming work across REST and WebSocket?
Both transports receive operations from the same transcriptService.ts source. REST clients poll /api/v1/sessions/{id}/transcript with pagination; WebSocket clients receive pushed ops after subscribing with agent_filter. The service maintains op-batch sequencing guarantees in both cases.
What controls whether search runs inline or in a worker thread?
The KIMI_CODE_EXPERIMENTAL_SEARCH_WORKER environment variable toggles execution mode. When set, search indexing and queries run in a dedicated worker thread to isolate CPU-heavy operations from request handling. Default behavior runs search inline in the main thread.
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:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →