ktx-data-agent-context-layer

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

ktx Data Agent Context Layer

ktx 数据Agent上下文层

Skill by ara.so — AI Agent Skills collection.
ktx is a self-improving context layer that teaches AI agents how to query data warehouses accurately. It automatically builds approved metric definitions, detects joinable columns, ingests business knowledge from wikis and dbt, and exposes everything through CLI and MCP interfaces.
ara.so提供的Skill——AI Agent技能合集。
ktx是一个可自我优化的上下文层,用于教会AI Agent如何准确查询数据仓库。它会自动构建已核准的指标定义、检测可关联列、从维基文档和dbt中提取业务知识,并通过CLI和MCP接口对外提供所有功能。

What ktx Does

ktx 功能介绍

  • Learns from company knowledge: Ingests wiki content, dbt docs, LookML, Metabase, and Notion; organizes it and flags contradictions
  • Maps the data stack: Samples tables, captures metadata, detects joinable columns, resolves fan/chasm traps
  • Builds semantic layer: Combines raw tables and high-level metrics through a join graph
  • Serves agents: Exposes CLI and MCP tools with full-text and semantic search
  • Read-only by design: Never writes to your warehouse
Supports PostgreSQL, Snowflake, BigQuery, ClickHouse, MySQL, SQL Server, SQLite. Integrates with dbt, MetricFlow, LookML, Looker, Metabase, Notion.
  • 学习企业知识:提取wiki内容、dbt文档、LookML、Metabase和Notion中的信息;进行整理并标记矛盾点
  • 映射数据栈:采样数据表、捕获元数据、检测可关联列、解决扇形/裂隙陷阱
  • 构建语义层:通过关联图结合原始数据表和高层指标
  • 为Agent提供服务:通过CLI和MCP工具提供全文检索和语义搜索功能
  • 只读设计:绝不会向你的数据仓库写入数据
支持PostgreSQL、Snowflake、BigQuery、ClickHouse、MySQL、SQL Server、SQLite。可与dbt、MetricFlow、LookML、Looker、Metabase、Notion集成。

Installation

安装步骤

Global CLI Installation

全局CLI安装

bash
npm install -g @kaelio/ktx
bash
npm install -g @kaelio/ktx

Project-Specific Setup

项目专属配置

bash
undefined
bash
undefined

Create or resume ktx project in current directory

在当前目录创建或恢复ktx项目

ktx setup
ktx setup

Check project readiness

检查项目就绪状态

ktx status
undefined
ktx status
undefined

Programmatic Installation (TypeScript)

程序化安装(TypeScript)

typescript
import { execSync } from 'child_process';

// Install ktx globally
execSync('npm install -g @kaelio/ktx', { stdio: 'inherit' });

// Initialize project
execSync('ktx setup', { 
  cwd: process.cwd(),
  stdio: 'inherit' 
});
typescript
import { execSync } from 'child_process';

// 全局安装ktx
execSync('npm install -g @kaelio/ktx', { stdio: 'inherit' });

// 初始化项目
execSync('ktx setup', { 
  cwd: process.cwd(),
  stdio: 'inherit' 
});

Project Structure

项目结构

After
ktx setup
, your project will contain:
my-project/
├── ktx.yaml                         # Project configuration
├── semantic-layer/<connection-id>/  # YAML semantic sources
├── wiki/global/                     # Shared business context
├── wiki/user/<user-id>/             # User-scoped notes
├── raw-sources/<connection-id>/     # Ingest artifacts and reports
└── .ktx/                            # Local state and secrets (git-ignored)
Important: Commit
ktx.yaml
,
semantic-layer/
, and
wiki/
. Keep
.ktx/
local and git-ignored.
执行
ktx setup
后,你的项目将包含以下结构:
my-project/
├── ktx.yaml                         # 项目配置文件
├── semantic-layer/<connection-id>/  # YAML语义源文件
├── wiki/global/                     # 共享业务上下文
├── wiki/user/<user-id>/             # 用户专属笔记
├── raw-sources/<connection-id>/     # 提取的工件和报告
└── .ktx/                            # 本地状态和密钥(已加入git忽略)
重要提示:提交
ktx.yaml
semantic-layer/
wiki/
到版本库。将
.ktx/
保留在本地并加入git忽略。

Configuration

配置说明

ktx.yaml Structure

ktx.yaml 结构

yaml
version: 1.0.0
projectName: my-analytics-project
yaml
version: 1.0.0
projectName: my-analytics-project

LLM Provider Configuration

LLM提供商配置

llmProvider: type: anthropic # or 'google-vertex', 'ai-gateway', 'claude-code' model: claude-sonnet-4-6

API key set via environment variable ANTHROPIC_API_KEY

llmProvider: type: anthropic # 或 'google-vertex', 'ai-gateway', 'claude-code' model: claude-sonnet-4-6

API密钥通过环境变量ANTHROPIC_API_KEY设置

Embedding Provider

嵌入模型提供商

embeddingProvider: type: openai model: text-embedding-3-small

API key set via environment variable OPENAI_API_KEY

embeddingProvider: type: openai model: text-embedding-3-small

API密钥通过环境变量OPENAI_API_KEY设置

Database Connections

数据库连接

connections:
  • id: warehouse type: postgres host: localhost port: 5432 database: analytics

    Credentials set via WAREHOUSE_USER and WAREHOUSE_PASSWORD

  • id: snowflake_prod type: snowflake account: xy12345.us-east-1 warehouse: COMPUTE_WH database: PROD schema: PUBLIC

    Credentials via SNOWFLAKE_USER and SNOWFLAKE_PASSWORD

connections:
  • id: warehouse type: postgres host: localhost port: 5432 database: analytics

    凭据通过WAREHOUSE_USER和WAREHOUSE_PASSWORD设置

  • id: snowflake_prod type: snowflake account: xy12345.us-east-1 warehouse: COMPUTE_WH database: PROD schema: PUBLIC

    凭据通过SNOWFLAKE_USER和SNOWFLAKE_PASSWORD设置

Context Sources

上下文源

contextSources:
  • id: dbt_main type: dbt manifestPath: ./target/manifest.json catalogPath: ./target/catalog.json
  • id: notion_wiki type: notion

    Token via NOTION_INTEGRATION_TOKEN

    databaseIds:
    • a1b2c3d4e5f6
  • id: metabase_analytics type: metabase url: https://metabase.company.com

    Credentials via METABASE_USER and METABASE_PASSWORD

undefined
contextSources:
  • id: dbt_main type: dbt manifestPath: ./target/manifest.json catalogPath: ./target/catalog.json
  • id: notion_wiki type: notion

    令牌通过NOTION_INTEGRATION_TOKEN设置

    databaseIds:
    • a1b2c3d4e5f6
  • id: metabase_analytics type: metabase url: https://metabase.company.com

    凭据通过METABASE_USER和METABASE_PASSWORD设置

undefined

Environment Variables

环境变量

Store credentials securely:
bash
undefined
安全存储凭据:
bash
undefined

LLM Providers

LLM提供商

export ANTHROPIC_API_KEY=sk-ant-... export OPENAI_API_KEY=sk-... export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json
export ANTHROPIC_API_KEY=sk-ant-... export OPENAI_API_KEY=sk-... export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json

Database Connections

数据库连接

export WAREHOUSE_USER=analytics_user export WAREHOUSE_PASSWORD=... export SNOWFLAKE_USER=... export SNOWFLAKE_PASSWORD=...
export WAREHOUSE_USER=analytics_user export WAREHOUSE_PASSWORD=... export SNOWFLAKE_USER=... export SNOWFLAKE_PASSWORD=...

Context Sources

上下文源

export NOTION_INTEGRATION_TOKEN=secret_... export METABASE_USER=... export METABASE_PASSWORD=...
export NOTION_INTEGRATION_TOKEN=secret_... export METABASE_USER=... export METABASE_PASSWORD=...

Optional: Specify project directory

可选:指定项目目录

export KTX_PROJECT_DIR=/path/to/project
undefined
export KTX_PROJECT_DIR=/path/to/project
undefined

Key Commands

核心命令

Setup and Status

配置与状态检查

bash
undefined
bash
undefined

Interactive setup wizard

交互式配置向导

ktx setup
ktx setup

Check project configuration and readiness

检查项目配置和就绪状态

ktx status
ktx status

Example output:

示例输出:

ktx project: /home/user/analytics

ktx project: /home/user/analytics

Project ready: yes

Project ready: yes

LLM ready: yes (claude-sonnet-4-6)

LLM ready: yes (claude-sonnet-4-6)

Databases configured: yes (warehouse)

Databases configured: yes (warehouse)

ktx context built: yes

ktx context built: yes

Agent integration ready: yes (codex:project)

Agent integration ready: yes (codex:project)

undefined
undefined

Building Context

构建上下文

bash
undefined
bash
undefined

Build context for all configured connections

为所有已配置的连接构建上下文

ktx ingest
ktx ingest

Build context for specific connection

为指定连接构建上下文

ktx ingest --connection warehouse
ktx ingest --connection warehouse

Force rebuild even if up-to-date

强制重建,即使当前已是最新状态

ktx ingest --force
ktx ingest --force

Dry run to see what would be ingested

试运行,查看将提取的内容

ktx ingest --dry-run
undefined
ktx ingest --dry-run
undefined

Searching Context

上下文搜索

bash
undefined
bash
undefined

Search semantic layer (metrics, dimensions, tables)

搜索语义层(指标、维度、数据表)

ktx sl "revenue" ktx sl "customer churn rate" ktx sl "monthly active users"
ktx sl "revenue" ktx sl "customer churn rate" ktx sl "monthly active users"

Search wiki content (business knowledge)

搜索wiki内容(业务知识)

ktx wiki "refund policy" ktx wiki "fiscal year definition" ktx wiki "customer segmentation"
ktx wiki "refund policy" ktx wiki "fiscal year definition" ktx wiki "customer segmentation"

Limit results

限制结果数量

ktx sl "orders" --limit 5 ktx wiki "pricing" --limit 3
undefined
ktx sl "orders" --limit 5 ktx wiki "pricing" --limit 3
undefined

MCP Server

MCP服务器

bash
undefined
bash
undefined

Start MCP server for agent integration

启动MCP服务器用于Agent集成

ktx mcp start
ktx mcp start

Specify project directory

指定项目目录

ktx mcp start --project-dir /path/to/project
ktx mcp start --project-dir /path/to/project

Check MCP status

检查MCP状态

ktx mcp status
ktx mcp status

Stop MCP server

停止MCP服务器

ktx mcp stop
undefined
ktx mcp stop
undefined

Maintenance

维护命令

bash
undefined
bash
undefined

Clear all cached context

清除所有缓存的上下文

ktx clear-cache
ktx clear-cache

Clear cache for specific connection

清除指定连接的缓存

ktx clear-cache --connection warehouse
ktx clear-cache --connection warehouse

Validate configuration without building

验证配置,无需构建上下文

ktx validate
ktx validate

Show version

显示版本

ktx --version
undefined
ktx --version
undefined

TypeScript API Usage

TypeScript API 使用

Programmatic Context Search

程序化上下文搜索

typescript
import { KtxClient } from '@kaelio/ktx';

// Initialize client
const ktx = new KtxClient({
  projectDir: process.cwd(),
  // Credentials from environment variables
});

// Search semantic layer
async function searchMetrics(query: string) {
  const results = await ktx.searchSemanticLayer(query, {
    limit: 10,
    includeScore: true
  });
  
  for (const result of results) {
    console.log(`${result.name} (score: ${result.score})`);
    console.log(`  Type: ${result.type}`);
    console.log(`  SQL: ${result.sql}`);
    console.log(`  Description: ${result.description}`);
  }
  
  return results;
}

// Search wiki
async function searchWiki(query: string) {
  const results = await ktx.searchWiki(query, {
    limit: 5,
    namespace: 'global'  // or 'user/<user-id>'
  });
  
  for (const result of results) {
    console.log(`${result.title}`);
    console.log(`  Path: ${result.path}`);
    console.log(`  Excerpt: ${result.excerpt}`);
  }
  
  return results;
}

// Usage
await searchMetrics('monthly revenue');
await searchWiki('customer retention strategy');
typescript
import { KtxClient } from '@kaelio/ktx';

// 初始化客户端
const ktx = new KtxClient({
  projectDir: process.cwd(),
  // 凭据从环境变量获取
});

// 搜索语义层
async function searchMetrics(query: string) {
  const results = await ktx.searchSemanticLayer(query, {
    limit: 10,
    includeScore: true
  });
  
  for (const result of results) {
    console.log(`${result.name} (score: ${result.score})`);
    console.log(`  Type: ${result.type}`);
    console.log(`  SQL: ${result.sql}`);
    console.log(`  Description: ${result.description}`);
  }
  
  return results;
}

// 搜索wiki
async function searchWiki(query: string) {
  const results = await ktx.searchWiki(query, {
    limit: 5,
    namespace: 'global'  // 或 'user/<user-id>'
  });
  
  for (const result of results) {
    console.log(`${result.title}`);
    console.log(`  Path: ${result.path}`);
    console.log(`  Excerpt: ${result.excerpt}`);
  }
  
  return results;
}

// 使用示例
await searchMetrics('monthly revenue');
await searchWiki('customer retention strategy');

Building Context Programmatically

程序化构建上下文

typescript
import { KtxClient } from '@kaelio/ktx';

async function buildContext() {
  const ktx = new KtxClient({
    projectDir: process.cwd()
  });
  
  // Ingest all sources
  await ktx.ingest({
    force: false,
    dryRun: false
  });
  
  // Ingest specific connection
  await ktx.ingest({
    connectionId: 'warehouse',
    force: true
  });
  
  console.log('Context built successfully');
}

await buildContext();
typescript
import { KtxClient } from '@kaelio/ktx';

async function buildContext() {
  const ktx = new KtxClient({
    projectDir: process.cwd()
  });
  
  // 提取所有源
  await ktx.ingest({
    force: false,
    dryRun: false
  });
  
  // 提取指定连接的源
  await ktx.ingest({
    connectionId: 'warehouse',
    force: true
  });
  
  console.log('上下文构建成功');
}

await buildContext();

Validating Configuration

验证配置

typescript
import { KtxClient } from '@kaelio/ktx';

async function validateProject() {
  const ktx = new KtxClient({
    projectDir: process.cwd()
  });
  
  const status = await ktx.getStatus();
  
  console.log('Project ready:', status.projectReady);
  console.log('LLM ready:', status.llmReady);
  console.log('Embeddings ready:', status.embeddingsReady);
  console.log('Databases configured:', status.databasesConfigured);
  console.log('Context built:', status.contextBuilt);
  console.log('Agent integration:', status.agentIntegration);
  
  if (!status.projectReady) {
    console.error('Issues:', status.issues);
  }
  
  return status.projectReady;
}

await validateProject();
typescript
import { KtxClient } from '@kaelio/ktx';

async function validateProject() {
  const ktx = new KtxClient({
    projectDir: process.cwd()
  });
  
  const status = await ktx.getStatus();
  
  console.log('项目就绪:', status.projectReady);
  console.log('LLM就绪:', status.llmReady);
  console.log('嵌入模型就绪:', status.embeddingsReady);
  console.log('数据库已配置:', status.databasesConfigured);
  console.log('上下文已构建:', status.contextBuilt);
  console.log('Agent集成:', status.agentIntegration);
  
  if (!status.projectReady) {
    console.error('问题:', status.issues);
  }
  
  return status.projectReady;
}

await validateProject();

Common Patterns

常见使用模式

Setting Up ktx for dbt Projects

为dbt项目配置ktx

bash
undefined
bash
undefined

Navigate to dbt project

进入dbt项目目录

cd my-dbt-project
cd my-dbt-project

Initialize ktx

初始化ktx

ktx setup
ktx setup

During setup, configure:

配置过程中需设置:

1. LLM provider (Anthropic recommended)

1. LLM提供商(推荐Anthropic)

2. Embedding provider (OpenAI recommended)

2. 嵌入模型提供商(推荐OpenAI)

3. Database connection (your data warehouse)

3. 数据库连接(你的数据仓库)

4. dbt context source (point to target/manifest.json)

4. dbt上下文源(指向target/manifest.json)

Build initial context

构建初始上下文

ktx ingest
ktx ingest

Search dbt models

搜索dbt模型

ktx sl "customer lifetime value"
undefined
ktx sl "customer lifetime value"
undefined

Integrating with Multiple Warehouses

与多个数据仓库集成

yaml
undefined
yaml
undefined

ktx.yaml

ktx.yaml

connections:
  • id: prod_warehouse type: snowflake account: prod.us-east-1 database: ANALYTICS
  • id: staging_warehouse type: postgres host: staging-db.internal database: analytics_staging
  • id: local_dev type: postgres host: localhost database: dev_analytics

```bash
connections:
  • id: prod_warehouse type: snowflake account: prod.us-east-1 database: ANALYTICS
  • id: staging_warehouse type: postgres host: staging-db.internal database: analytics_staging
  • id: local_dev type: postgres host: localhost database: dev_analytics

```bash

Ingest each warehouse

提取每个数据仓库的内容

ktx ingest --connection prod_warehouse ktx ingest --connection staging_warehouse ktx ingest --connection local_dev
ktx ingest --connection prod_warehouse ktx ingest --connection staging_warehouse ktx ingest --connection local_dev

Search across all warehouses

跨所有数据仓库搜索

ktx sl "daily_revenue"
undefined
ktx sl "daily_revenue"
undefined

Creating Semantic Layer Definitions

创建语义层定义

Create
semantic-layer/<connection-id>/metrics.yaml
:
yaml
metrics:
  - name: monthly_recurring_revenue
    description: Total MRR from active subscriptions
    type: metric
    sql: |
      SELECT 
        DATE_TRUNC('month', subscription_start) as month,
        SUM(monthly_amount) as mrr
      FROM subscriptions
      WHERE status = 'active'
      GROUP BY 1
    dimensions:
      - month
    measures:
      - mrr
    grain: monthly
    
  - name: customer_churn_rate
    description: Percentage of customers who churned in period
    type: metric
    sql: |
      SELECT
        DATE_TRUNC('month', churn_date) as month,
        COUNT(DISTINCT customer_id)::float / 
        LAG(COUNT(DISTINCT customer_id)) OVER (ORDER BY DATE_TRUNC('month', churn_date)) as churn_rate
      FROM customers
      WHERE churned = true
      GROUP BY 1
    dimensions:
      - month
    measures:
      - churn_rate
    grain: monthly
bash
undefined
创建
semantic-layer/<connection-id>/metrics.yaml
:
yaml
metrics:
  - name: monthly_recurring_revenue
    description: Total MRR from active subscriptions
    type: metric
    sql: |
      SELECT 
        DATE_TRUNC('month', subscription_start) as month,
        SUM(monthly_amount) as mrr
      FROM subscriptions
      WHERE status = 'active'
      GROUP BY 1
    dimensions:
      - month
    measures:
      - mrr
    grain: monthly
    
  - name: customer_churn_rate
    description: Percentage of customers who churned in period
    type: metric
    sql: |
      SELECT
        DATE_TRUNC('month', churn_date) as month,
        COUNT(DISTINCT customer_id)::float / 
        LAG(COUNT(DISTINCT customer_id)) OVER (ORDER BY DATE_TRUNC('month', churn_date)) as churn_rate
      FROM customers
      WHERE churned = true
      GROUP BY 1
    dimensions:
      - month
    measures:
      - churn_rate
    grain: monthly
bash
undefined

Rebuild to pick up new definitions

强制重建以加载新定义

ktx ingest --force
undefined
ktx ingest --force
undefined

Adding Wiki Knowledge

添加Wiki知识

Create
wiki/global/pricing-policy.md
:
markdown
undefined
创建
wiki/global/pricing-policy.md
:
markdown
undefined

Pricing Policy

定价政策

Standard Pricing Tiers

标准定价层级

  • Basic: $29/month, up to 10 users
  • Professional: $99/month, up to 50 users
  • Enterprise: Custom pricing, unlimited users
  • 基础版:每月29美元,最多10名用户
  • 专业版:每月99美元,最多50名用户
  • 企业版:定制定价,无用户数量限制

Discounts

折扣政策

  • Annual commitment: 20% off
  • Non-profit organizations: 30% off
  • Educational institutions: 50% off
  • 年度订阅:享受20%折扣
  • 非营利组织:享受30%折扣
  • 教育机构:享受50%折扣

Refund Policy

退款政策

Full refund within 30 days of purchase, no questions asked. After 30 days, prorated refund for annual plans only.
购买后30天内可全额退款,无需理由。 30天后,仅年度计划可享受按比例退款。

Fiscal Year

财年定义

Our fiscal year runs from February 1 to January 31. Q1 = Feb-Apr, Q2 = May-Jul, Q3 = Aug-Oct, Q4 = Nov-Jan

```bash
我们的财年为2月1日至次年1月31日。 Q1 = 2-4月,Q2 = 5-7月,Q3 = 8-10月,Q4 = 11-1月

```bash

Rebuild to index wiki content

重建以索引wiki内容

ktx ingest
ktx ingest

Search wiki

搜索wiki

ktx wiki "refund policy" ktx wiki "fiscal year Q1"
undefined
ktx wiki "refund policy" ktx wiki "fiscal year Q1"
undefined

Agent Integration Workflow

Agent集成工作流

bash
undefined
bash
undefined

1. Setup ktx in your project

1. 在你的项目中配置ktx

ktx setup
ktx setup

2. Build context

2. 构建上下文

ktx ingest
ktx ingest

3. Start MCP server

3. 启动MCP服务器

ktx mcp start --project-dir $(pwd)
ktx mcp start --project-dir $(pwd)

4. In your agent (Claude Code, Codex, etc.), use ktx tools:

4. 在你的Agent(Claude Code、Codex等)中使用ktx工具:

- search_semantic_layer: Find metrics and tables

- search_semantic_layer: 查找指标和数据表

- search_wiki: Find business knowledge

- search_wiki: 查找业务知识

- get_metric_definition: Get approved SQL for a metric

- get_metric_definition: 获取指标的核准SQL定义

- list_connections: See available data sources

- list_connections: 查看可用数据源

Example agent prompt:

Agent提示示例:

"Use ktx to search for revenue metrics and show me the approved SQL definition"

"使用ktx搜索收入指标并展示其核准的SQL定义"

undefined
undefined

Troubleshooting

故障排除

ktx setup fails with "LLM provider not configured"

ktx setup执行失败,提示"LLM provider not configured"

Solution: Set required environment variables:
bash
export ANTHROPIC_API_KEY=sk-ant-...
解决方案:设置所需环境变量:
bash
export ANTHROPIC_API_KEY=sk-ant-...

or

export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json
undefined
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json
undefined

ktx ingest fails with "Connection refused"

ktx ingest执行失败,提示"Connection refused"

Problem: Database connection credentials incorrect or host unreachable.
Solution: Verify connection in
ktx.yaml
and test manually:
bash
undefined
问题:数据库连接凭据错误或主机无法访问。
解决方案:验证
ktx.yaml
中的连接信息并手动测试:
bash
undefined

For PostgreSQL

PostgreSQL测试

psql -h localhost -U analytics_user -d analytics
psql -h localhost -U analytics_user -d analytics

For Snowflake

Snowflake测试

snowsql -a xy12345.us-east-1 -u username -d PROD
undefined
snowsql -a xy12345.us-east-1 -u username -d PROD
undefined

ktx status shows "Agent integration ready: no"

ktx status显示"Agent integration ready: no"

Problem: MCP server not started or not configured for agent.
Solution: Start MCP server:
bash
ktx mcp start
问题:MCP服务器未启动或未为Agent配置。
解决方案:启动MCP服务器:
bash
ktx mcp start

If using Codex, ensure .codex/skills.yaml includes ktx

如果使用Codex,确保.codex/skills.yaml包含ktx

If using Claude Code, ensure Claude can access MCP server

如果使用Claude Code,确保Claude可以访问MCP服务器

undefined
undefined

Search returns no results

搜索无结果返回

Problem: Context not built or out of date.
Solution: Rebuild context:
bash
ktx ingest --force
问题:上下文未构建或已过期。
解决方案:重建上下文:
bash
ktx ingest --force

"Module not found" when importing @kaelio/ktx

导入@kaelio/ktx时提示"Module not found"

Problem: Package not installed or not in node_modules.
Solution:
bash
undefined
问题:包未安装或不在node_modules中。
解决方案:
bash
undefined

Install globally for CLI

全局安装用于CLI

npm install -g @kaelio/ktx
npm install -g @kaelio/ktx

Install locally for programmatic use

本地安装用于程序化调用

npm install @kaelio/ktx
undefined
npm install @kaelio/ktx
undefined

Semantic layer definitions not appearing

语义层定义未显示

Problem: YAML files in wrong location or invalid syntax.
Solution: Verify structure:
bash
undefined
问题:YAML文件位置错误或语法无效。
解决方案:验证结构:
bash
undefined

Files must be in semantic-layer/<connection-id>/*.yaml

文件必须位于semantic-layer/<connection-id>/*.yaml

ls -la semantic-layer/warehouse/
ls -la semantic-layer/warehouse/

Validate YAML syntax

验证YAML语法

ktx validate
undefined
ktx validate
undefined

MCP server crashes on startup

MCP服务器启动时崩溃

Problem: Port conflict or invalid project directory.
Solution:
bash
undefined
问题:端口冲突或项目目录无效。
解决方案:
bash
undefined

Check if another ktx instance is running

检查是否有其他ktx实例在运行

ktx mcp status
ktx mcp status

Stop existing instance

停止现有实例

ktx mcp stop
ktx mcp stop

Verify project directory

验证项目目录

ktx status --project-dir $(pwd)
undefined
ktx status --project-dir $(pwd)
undefined

"Read-only violation" error

出现"Read-only violation"错误

Problem: ktx attempted to write to database (should never happen).
Solution: This is a bug. Report it:
bash
undefined
问题:ktx尝试向数据库写入数据(本不应发生)。
解决方案:这是一个bug,请提交报告:
bash
undefined

Check ktx version

检查ktx版本

ktx --version
ktx --version

Report to GitHub Issues with connection type and error details

携带连接类型和错误详情向GitHub Issues提交报告

undefined
undefined

Development and Testing

开发与测试

Running ktx in Development Mode

开发模式运行ktx

bash
undefined
bash
undefined

Clone repository

克隆仓库

Install dependencies

安装依赖

pnpm install uv sync --all-groups
pnpm install uv sync --all-groups

Build project

构建项目

pnpm run build
pnpm run build

Run type checks

运行类型检查

pnpm run type-check
pnpm run type-check

Run tests

运行测试

pnpm run test uv run pytest -q
pnpm run test uv run pytest -q

Link development CLI

链接开发版CLI

pnpm run setup:dev pnpm run link:dev
pnpm run setup:dev pnpm run link:dev

Use development version

使用开发版本

ktx-dev --help
undefined
ktx-dev --help
undefined

Testing ktx Integration

测试ktx集成

typescript
import { KtxClient } from '@kaelio/ktx';
import { describe, it, expect } from 'vitest';

describe('ktx integration', () => {
  const ktx = new KtxClient({
    projectDir: './test-project'
  });
  
  it('should search semantic layer', async () => {
    const results = await ktx.searchSemanticLayer('revenue', {
      limit: 5
    });
    
    expect(results).toBeDefined();
    expect(results.length).toBeGreaterThan(0);
    expect(results[0]).toHaveProperty('name');
    expect(results[0]).toHaveProperty('sql');
  });
  
  it('should search wiki', async () => {
    const results = await ktx.searchWiki('pricing', {
      limit: 3,
      namespace: 'global'
    });
    
    expect(results).toBeDefined();
    expect(results[0]).toHaveProperty('title');
    expect(results[0]).toHaveProperty('excerpt');
  });
  
  it('should validate project status', async () => {
    const status = await ktx.getStatus();
    
    expect(status.projectReady).toBe(true);
    expect(status.llmReady).toBe(true);
    expect(status.contextBuilt).toBe(true);
  });
});
typescript
import { KtxClient } from '@kaelio/ktx';
import { describe, it, expect } from 'vitest';

describe('ktx integration', () => {
  const ktx = new KtxClient({
    projectDir: './test-project'
  });
  
  it('should search semantic layer', async () => {
    const results = await ktx.searchSemanticLayer('revenue', {
      limit: 5
    });
    
    expect(results).toBeDefined();
    expect(results.length).toBeGreaterThan(0);
    expect(results[0]).toHaveProperty('name');
    expect(results[0]).toHaveProperty('sql');
  });
  
  it('should search wiki', async () => {
    const results = await ktx.searchWiki('pricing', {
      limit: 3,
      namespace: 'global'
    });
    
    expect(results).toBeDefined();
    expect(results[0]).toHaveProperty('title');
    expect(results[0]).toHaveProperty('excerpt');
  });
  
  it('should validate project status', async () => {
    const status = await ktx.getStatus();
    
    expect(status.projectReady).toBe(true);
    expect(status.llmReady).toBe(true);
    expect(status.contextBuilt).toBe(true);
  });
});

Additional Resources

额外资源