ktx-ai-data-agents-context-layer
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinesektx AI Data Agents Context Layer
ktx AI数据Agent上下文层
Overview
概述
ktx is a self-improving context layer that teaches AI agents how to query your data warehouse accurately. It combines:
- Automatic context building from your warehouse schema, usage patterns, and joinable columns
- Semantic layer with approved metric definitions and automatic join graph resolution
- Wiki integration that absorbs knowledge from dbt, Looker, Metabase, Notion, and team documentation
- MCP server that exposes tools for agent execution with full-text and semantic search
ktx runs locally with your own LLM API keys (Anthropic, Google Vertex AI, AI Gateway, or Claude Code session). No hosted service, no extra usage billing.
ktx是一个自我优化的上下文层,能够教会AI Agent如何精准查询你的数据仓库。它整合了以下功能:
- 自动上下文构建:从你的仓库 schema、使用模式和可关联列生成上下文
- 语义层:包含已审批的指标定义和自动关联图解析
- Wiki集成:从dbt、Looker、Metabase、Notion和团队文档中吸收知识
- MCP服务器:提供Agent执行工具,支持全文检索和语义搜索
ktx本地运行,使用你自己的LLM API密钥(Anthropic、Google Vertex AI、AI Gateway或Claude Code会话)。无需托管服务,无额外使用费用。
Installation
安装
Global installation
全局安装
bash
npm install -g @kaelio/ktxbash
npm install -g @kaelio/ktxProject-specific installation
项目专属安装
bash
cd my-analytics-project
npx @kaelio/ktx setupbash
cd my-analytics-project
npx @kaelio/ktx setupRequirements
要求
- Node.js 18+
- Python 3.9+ (for semantic layer query planning)
- A SQL warehouse: PostgreSQL, Snowflake, BigQuery, ClickHouse, MySQL, SQL Server, or SQLite
- LLM provider: Anthropic API, Google Vertex AI, AI Gateway, or Claude Code
- Node.js 18+
- Python 3.9+(用于语义层查询规划)
- SQL仓库:PostgreSQL、Snowflake、BigQuery、ClickHouse、MySQL、SQL Server或SQLite
- LLM提供商:Anthropic API、Google Vertex AI、AI Gateway或Claude Code
Quick Setup
快速设置
bash
undefinedbash
undefinedCreate or resume a ktx project
创建或恢复ktx项目
ktx setup
ktx setup
Check project readiness
检查项目就绪状态
ktx status
ktx status
Build context from all configured sources
从所有配置源构建上下文
ktx ingest
ktx ingest
Start MCP server for agent integration
启动MCP服务器用于Agent集成
ktx mcp start
The `ktx setup` command walks through:
1. LLM provider configuration (API keys stored in `.ktx/`)
2. Database connection setup
3. Context source configuration (dbt, Looker, Metabase, Notion)
4. Initial context ingestion
5. Agent integration (Claude Code, Codex, Cursor, OpenCode)ktx mcp start
`ktx setup`命令将引导你完成以下步骤:
1. LLM提供商配置(API密钥存储在`.ktx/`中)
2. 数据库连接设置
3. 上下文源配置(dbt、Looker、Metabase、Notion)
4. 初始上下文导入
5. Agent集成(Claude Code、Codex、Cursor、OpenCode)Project Structure
项目结构
my-project/
├── ktx.yaml # Project configuration (commit)
├── semantic-layer/<connection-id>/ # YAML semantic sources (commit)
├── wiki/global/ # Shared business context (commit)
├── wiki/user/<user-id>/ # User-scoped notes (commit)
├── raw-sources/<connection-id>/ # Ingest artifacts and reports (commit)
└── .ktx/ # Local state and secrets (git-ignore)my-project/
├── ktx.yaml # 项目配置(需提交)
├── semantic-layer/<connection-id>/ # YAML语义源(需提交)
├── wiki/global/ # 共享业务上下文(需提交)
├── wiki/user/<user-id>/ # 用户专属笔记(需提交)
├── raw-sources/<connection-id>/ # 导入产物和报告(需提交)
└── .ktx/ # 本地状态和密钥(需忽略git提交)Configuration
配置
ktx.yaml
ktx.yaml
yaml
version: 1
projectName: my-analytics
llmProvider: anthropic # or google-vertex, ai-gateway, claude-agent-sdk
embeddingProvider: openai
databases:
warehouse:
type: postgres # or snowflake, bigquery, clickhouse, mysql, mssql, sqlite
host: "${DB_HOST}"
port: 5432
database: "${DB_NAME}"
user: "${DB_USER}"
password: "${DB_PASSWORD}"
# For read-only safety:
readOnly: true
contextSources:
dbt_main:
type: dbt
manifestPath: ./target/manifest.json
catalogPath: ./target/catalog.json
looker_metrics:
type: lookml
projectPath: ./looker
company_wiki:
type: notion
apiKey: "${NOTION_API_KEY}"
databaseId: "${NOTION_DATABASE_ID}"yaml
version: 1
projectName: my-analytics
llmProvider: anthropic # 或google-vertex, ai-gateway, claude-agent-sdk
embeddingProvider: openai
databases:
warehouse:
type: postgres # 或snowflake, bigquery, clickhouse, mysql, mssql, sqlite
host: "${DB_HOST}"
port: 5432
database: "${DB_NAME}"
user: "${DB_USER}"
password: "${DB_PASSWORD}"
# 只读安全设置:
readOnly: true
contextSources:
dbt_main:
type: dbt
manifestPath: ./target/manifest.json
catalogPath: ./target/catalog.json
looker_metrics:
type: lookml
projectPath: ./looker
company_wiki:
type: notion
apiKey: "${NOTION_API_KEY}"
databaseId: "${NOTION_DATABASE_ID}"Environment variables
环境变量
Store secrets in or your shell environment:
.ktx/envbash
export ANTHROPIC_API_KEY=sk-ant-...
export OPENAI_API_KEY=sk-...
export DB_HOST=warehouse.company.com
export DB_USER=readonly_user
export DB_PASSWORD=...
export NOTION_API_KEY=secret_...将密钥存储在或你的Shell环境中:
.ktx/envbash
export ANTHROPIC_API_KEY=sk-ant-...
export OPENAI_API_KEY=sk-...
export DB_HOST=warehouse.company.com
export DB_USER=readonly_user
export DB_PASSWORD=...
export NOTION_API_KEY=secret_...Key Commands
核心命令
Project management
项目管理
bash
undefinedbash
undefinedInitialize or resume project
初始化或恢复项目
ktx setup
ktx setup
Check configuration and readiness
检查配置和就绪状态
ktx status
ktx status
Validate configuration without running ingestion
验证配置(不执行导入)
ktx validate
undefinedktx validate
undefinedContext building
上下文构建
bash
undefinedbash
undefinedIngest all configured sources
导入所有配置源
ktx ingest
ktx ingest
Ingest specific connection
导入指定连接
ktx ingest --connection warehouse
ktx ingest --connection warehouse
Force re-ingestion (skip cache)
强制重新导入(跳过缓存)
ktx ingest --force
ktx ingest --force
Dry run to preview changes
试运行以预览变更
ktx ingest --dry-run
undefinedktx ingest --dry-run
undefinedSearching context
上下文搜索
bash
undefinedbash
undefinedSearch semantic layer (metrics, dimensions, sources)
搜索语义层(指标、维度、源)
ktx sl "revenue"
ktx sl "customer churn rate"
ktx sl "revenue"
ktx sl "customer churn rate"
Search wiki pages
搜索Wiki页面
ktx wiki "refund policy"
ktx wiki "data governance"
ktx wiki "refund policy"
ktx wiki "data governance"
Combined search across all context
跨所有上下文的组合搜索
ktx search "active users"
undefinedktx search "active users"
undefinedMCP server
MCP服务器
bash
undefinedbash
undefinedStart MCP server for agent clients
启动MCP服务器供Agent客户端使用
ktx mcp start
ktx mcp start
Start with custom project directory
使用自定义项目目录启动
ktx mcp start --project-dir /path/to/project
ktx mcp start --project-dir /path/to/project
Check MCP server status
检查MCP服务器状态
ktx mcp status
ktx mcp status
Stop MCP server
停止MCP服务器
ktx mcp stop
undefinedktx mcp stop
undefinedSemantic layer operations
语义层操作
bash
undefinedbash
undefinedList all semantic sources
列出所有语义源
ktx sl list
ktx sl list
Describe a specific metric
描述指定指标
ktx sl describe revenue_total
ktx sl describe revenue_total
Validate semantic layer definitions
验证语义层定义
ktx sl validate
ktx sl validate
Export semantic layer to JSON
将语义层导出为JSON
ktx sl export --output ./semantic-layer.json
undefinedktx sl export --output ./semantic-layer.json
undefinedWorking with Database Connections
数据库连接使用
PostgreSQL
PostgreSQL
typescript
// In ktx.yaml
databases:
warehouse:
type: postgres
host: "${POSTGRES_HOST}"
port: 5432
database: "${POSTGRES_DB}"
user: "${POSTGRES_USER}"
password: "${POSTGRES_PASSWORD}"
schema: public # Optional: default schema
readOnly: truetypescript
// 在ktx.yaml中
databases:
warehouse:
type: postgres
host: "${POSTGRES_HOST}"
port: 5432
database: "${POSTGRES_DB}"
user: "${POSTGRES_USER}"
password: "${POSTGRES_PASSWORD}"
schema: public # 可选:默认schema
readOnly: trueSnowflake
Snowflake
yaml
databases:
snowflake_prod:
type: snowflake
account: "${SNOWFLAKE_ACCOUNT}"
warehouse: "${SNOWFLAKE_WAREHOUSE}"
database: "${SNOWFLAKE_DATABASE}"
schema: "${SNOWFLAKE_SCHEMA}"
user: "${SNOWFLAKE_USER}"
password: "${SNOWFLAKE_PASSWORD}"
role: ANALYST # Optional
readOnly: trueyaml
databases:
snowflake_prod:
type: snowflake
account: "${SNOWFLAKE_ACCOUNT}"
warehouse: "${SNOWFLAKE_WAREHOUSE}"
database: "${SNOWFLAKE_DATABASE}"
schema: "${SNOWFLAKE_SCHEMA}"
user: "${SNOWFLAKE_USER}"
password: "${SNOWFLAKE_PASSWORD}"
role: ANALYST # 可选
readOnly: trueBigQuery
BigQuery
yaml
databases:
bigquery_prod:
type: bigquery
projectId: "${GCP_PROJECT_ID}"
datasetId: "${BQ_DATASET_ID}"
keyFilePath: "${GOOGLE_APPLICATION_CREDENTIALS}"
readOnly: trueyaml
databases:
bigquery_prod:
type: bigquery
projectId: "${GCP_PROJECT_ID}"
datasetId: "${BQ_DATASET_ID}"
keyFilePath: "${GOOGLE_APPLICATION_CREDENTIALS}"
readOnly: trueContext Source Integration
上下文源集成
dbt
dbt
yaml
contextSources:
dbt_main:
type: dbt
manifestPath: ./target/manifest.json
catalogPath: ./target/catalog.json
# Optional: filter to specific models
includePatterns:
- "mart_*"
- "dim_*"
- "fct_*"Before ingesting, ensure dbt artifacts are up to date:
bash
dbt compile
dbt docs generate
ktx ingest --connection dbt_mainyaml
contextSources:
dbt_main:
type: dbt
manifestPath: ./target/manifest.json
catalogPath: ./target/catalog.json
# 可选:过滤指定模型
includePatterns:
- "mart_*"
- "dim_*"
- "fct_*"导入前,确保dbt产物是最新的:
bash
dbt compile
dbt docs generate
ktx ingest --connection dbt_mainLooker / LookML
Looker / LookML
yaml
contextSources:
looker_metrics:
type: lookml
projectPath: ./looker-project
# Optional: specific view files
includePatterns:
- "views/metrics/*.lkml"yaml
contextSources:
looker_metrics:
type: lookml
projectPath: ./looker-project
# 可选:指定视图文件
includePatterns:
- "views/metrics/*.lkml"Metabase
Metabase
yaml
contextSources:
metabase_metrics:
type: metabase
apiUrl: "${METABASE_URL}"
apiKey: "${METABASE_API_KEY}"
# Optional: filter to specific collections
collectionIds:
- 42
- 57yaml
contextSources:
metabase_metrics:
type: metabase
apiUrl: "${METABASE_URL}"
apiKey: "${METABASE_API_KEY}"
# 可选:过滤指定集合
collectionIds:
- 42
- 57Notion
Notion
yaml
contextSources:
company_wiki:
type: notion
apiKey: "${NOTION_API_KEY}"
databaseId: "${NOTION_DATABASE_ID}"
# Optional: filter by tags or properties
filters:
tags:
- analytics
- data-dictionaryyaml
contextSources:
company_wiki:
type: notion
apiKey: "${NOTION_API_KEY}"
databaseId: "${NOTION_DATABASE_ID}"
# 可选:按标签或属性过滤
filters:
tags:
- analytics
- data-dictionarySemantic Layer Definitions
语义层定义
Basic metric
基础指标
yaml
undefinedyaml
undefinedsemantic-layer/warehouse/revenue_total.yaml
semantic-layer/warehouse/revenue_total.yaml
apiVersion: v1
kind: Metric
metadata:
name: revenue_total
display_name: Total Revenue
description: Sum of all completed order amounts
spec:
type: measure
aggregation: sum
sql: "{{source.orders}}.amount"
filters:
- "{{source.orders}}.status = 'completed'"
dimensions:
- date
- customer_id
- product_id
undefinedapiVersion: v1
kind: Metric
metadata:
name: revenue_total
display_name: Total Revenue
description: Sum of all completed order amounts
spec:
type: measure
aggregation: sum
sql: "{{source.orders}}.amount"
filters:
- "{{source.orders}}.status = 'completed'"
dimensions:
- date
- customer_id
- product_id
undefinedDerived metric
派生指标
yaml
undefinedyaml
undefinedsemantic-layer/warehouse/revenue_per_customer.yaml
semantic-layer/warehouse/revenue_per_customer.yaml
apiVersion: v1
kind: Metric
metadata:
name: revenue_per_customer
display_name: Revenue per Customer
description: Average revenue per unique customer
spec:
type: ratio
numerator: revenue_total
denominator: customers_count
dimensions:
- date
- region
undefinedapiVersion: v1
kind: Metric
metadata:
name: revenue_per_customer
display_name: Revenue per Customer
description: Average revenue per unique customer
spec:
type: ratio
numerator: revenue_total
denominator: customers_count
dimensions:
- date
- region
undefinedDimension
维度
yaml
undefinedyaml
undefinedsemantic-layer/warehouse/customer_segment.yaml
semantic-layer/warehouse/customer_segment.yaml
apiVersion: v1
kind: Dimension
metadata:
name: customer_segment
display_name: Customer Segment
description: Customer categorization by lifetime value
spec:
type: categorical
sql: |
CASE
WHEN {{source.customers}}.lifetime_value > 10000 THEN 'enterprise'
WHEN {{source.customers}}.lifetime_value > 1000 THEN 'mid-market'
ELSE 'smb'
END
source: customers
undefinedapiVersion: v1
kind: Dimension
metadata:
name: customer_segment
display_name: Customer Segment
description: Customer categorization by lifetime value
spec:
type: categorical
sql: |
CASE
WHEN {{source.customers}}.lifetime_value > 10000 THEN 'enterprise'
WHEN {{source.customers}}.lifetime_value > 1000 THEN 'mid-market'
ELSE 'smb'
END
source: customers
undefinedSource table
源表
yaml
undefinedyaml
undefinedsemantic-layer/warehouse/orders.yaml
semantic-layer/warehouse/orders.yaml
apiVersion: v1
kind: Source
metadata:
name: orders
display_name: Orders
description: All customer orders
spec:
table: public.orders
primaryKey: id
joins:
- name: customers
type: left
sql: "{{source.orders}}.customer_id = {{source.customers}}.id"
- name: products
type: left
sql: "{{source.orders}}.product_id = {{source.products}}.id"
columns:
- name: id
type: integer
primaryKey: true
- name: customer_id
type: integer
- name: product_id
type: integer
- name: amount
type: decimal
- name: status
type: string
- name: created_at
type: timestamp
undefinedapiVersion: v1
kind: Source
metadata:
name: orders
display_name: Orders
description: All customer orders
spec:
table: public.orders
primaryKey: id
joins:
- name: customers
type: left
sql: "{{source.orders}}.customer_id = {{source.customers}}.id"
- name: products
type: left
sql: "{{source.orders}}.product_id = {{source.products}}.id"
columns:
- name: id
type: integer
primaryKey: true
- name: customer_id
type: integer
- name: product_id
type: integer
- name: amount
type: decimal
- name: status
type: string
- name: created_at
type: timestamp
undefinedAgent Integration
Agent集成
Claude Code
Claude Code
After running , ktx installs itself as an MCP server. In Claude Code:
ktx setupbash
undefined运行后,ktx会将自身安装为MCP服务器。在Claude Code中:
ktx setupbash
undefinedFrom your project directory
从你的项目目录
ktx mcp start --project-dir .
Then in Claude Code, verify MCP server is connected:
/mcp-servers
You should see `ktx` listed. Now ask:
Use ktx to show me total revenue by month for the last quarter
undefinedktx mcp start --project-dir .
然后在Claude Code中,验证MCP服务器已连接:
/mcp-servers
你应该会看到`ktx`被列出。现在可以提问:
Use ktx to show me total revenue by month for the last quarter
undefinedCodex
Codex
bash
undefinedbash
undefinedInstall ktx skill in Codex
在Codex中安装ktx skill
npx skills add Kaelio/ktx --skill ktx
npx skills add Kaelio/ktx --skill ktx
Verify installation
验证安装
npx skills list
Then in Codex:
@ktx search for customer churn metrics
undefinednpx skills list
然后在Codex中:
@ktx search for customer churn metrics
undefinedCursor / OpenCode
Cursor / OpenCode
Configure MCP server in settings:
json
{
"mcpServers": {
"ktx": {
"command": "ktx",
"args": ["mcp", "start", "--project-dir", "${workspaceFolder}"]
}
}
}在设置中配置MCP服务器:
json
{
"mcpServers": {
"ktx": {
"command": "ktx",
"args": ["mcp", "start", "--project-dir", "${workspaceFolder}"]
}
}
}MCP Tools
MCP工具
When the MCP server is running, agents can call:
当MCP服务器运行时,Agent可以调用以下工具:
ktx_search_semantic_layer
ktx_search_semantic_layerktx_search_semantic_layer
ktx_search_semantic_layertypescript
// Agent calls this tool
{
"tool": "ktx_search_semantic_layer",
"arguments": {
"query": "revenue by customer segment",
"limit": 10
}
}Returns ranked results with metric definitions, SQL, dimensions, and filters.
typescript
// Agent调用此工具
{
"tool": "ktx_search_semantic_layer",
"arguments": {
"query": "revenue by customer segment",
"limit": 10
}
}返回包含指标定义、SQL、维度和过滤器的排序结果。
ktx_search_wiki
ktx_search_wikiktx_search_wiki
ktx_search_wikitypescript
{
"tool": "ktx_search_wiki",
"arguments": {
"query": "refund policy",
"limit": 5
}
}Returns wiki pages with full-text and semantic search.
typescript
{
"tool": "ktx_search_wiki",
"arguments": {
"query": "refund policy",
"limit": 5
}
}返回支持全文检索和语义搜索的Wiki页面。
ktx_get_metric
ktx_get_metricktx_get_metric
ktx_get_metrictypescript
{
"tool": "ktx_get_metric",
"arguments": {
"metricName": "revenue_total"
}
}Returns full metric definition, SQL, join graph, and usage examples.
typescript
{
"tool": "ktx_get_metric",
"arguments": {
"metricName": "revenue_total"
}
}返回完整的指标定义、SQL、关联图和使用示例。
ktx_list_sources
ktx_list_sourcesktx_list_sources
ktx_list_sourcestypescript
{
"tool": "ktx_list_sources",
"arguments": {
"connectionId": "warehouse"
}
}Returns all semantic sources (tables) for a connection.
typescript
{
"tool": "ktx_list_sources",
"arguments": {
"connectionId": "warehouse"
}
}返回指定连接的所有语义源(表)。
ktx_validate_query
ktx_validate_queryktx_validate_query
ktx_validate_querytypescript
{
"tool": "ktx_validate_query",
"arguments": {
"sql": "SELECT revenue_total FROM metrics WHERE date > '2024-01-01'",
"connectionId": "warehouse"
}
}Validates SQL against semantic layer and returns suggestions.
typescript
{
"tool": "ktx_validate_query",
"arguments": {
"sql": "SELECT revenue_total FROM metrics WHERE date > '2024-01-01'",
"connectionId": "warehouse"
}
}根据语义层验证SQL并返回建议。
Common Patterns
常见模式
Initial setup for a new project
新项目初始设置
bash
undefinedbash
undefinedNavigate to your analytics project
导航到你的分析项目
cd my-analytics-project
cd my-analytics-project
Initialize ktx
初始化ktx
ktx setup
ktx setup
Configure LLM provider (follow prompts)
配置LLM提供商(跟随提示)
- Choose anthropic, google-vertex, or ai-gateway
- 选择anthropic、google-vertex或ai-gateway
- Enter API key (stored in .ktx/env)
- 输入API密钥(存储在.ktx/env中)
Configure database connection
配置数据库连接
- Choose your warehouse type
- 选择你的仓库类型
- Enter connection details
- 输入连接详情
- Test connection
- 测试连接
Add context sources
添加上下文源
- Select dbt, lookml, metabase, or notion
- 选择dbt、lookml、metabase或notion
- Provide paths or API credentials
- 提供路径或API凭证
Build initial context
构建初始上下文
ktx ingest
ktx ingest
Verify everything is ready
验证所有内容已就绪
ktx status
undefinedktx status
undefinedDaily workflow
日常工作流
bash
undefinedbash
undefinedUpdate context after schema changes
架构变更后更新上下文
ktx ingest
ktx ingest
Search for a metric
搜索指标
ktx sl "active users"
ktx sl "active users"
Get metric SQL
获取指标SQL
ktx sl describe active_users_monthly
ktx sl describe active_users_monthly
Start MCP server for agent work
启动MCP服务器用于Agent工作
ktx mcp start
undefinedktx mcp start
undefinedAdding a new metric
添加新指标
bash
undefinedbash
undefinedCreate YAML in semantic-layer/<connection-id>/
在semantic-layer/<connection-id>/中创建YAML
cat > semantic-layer/warehouse/new_metric.yaml <<EOF
apiVersion: v1
kind: Metric
metadata:
name: new_metric
display_name: New Metric
description: Description of what this measures
spec:
type: measure
aggregation: sum
sql: "{{source.table}}.column"
dimensions:
- date
EOF
cat > semantic-layer/warehouse/new_metric.yaml <<EOF
apiVersion: v1
kind: Metric
metadata:
name: new_metric
display_name: New Metric
description: Description of what this measures
spec:
type: measure
aggregation: sum
sql: "{{source.table}}.column"
dimensions:
- date
EOF
Validate
验证
ktx sl validate
ktx sl validate
Re-ingest to make available
重新导入使其可用
ktx ingest
undefinedktx ingest
undefinedTroubleshooting connection issues
连接问题排查
bash
undefinedbash
undefinedTest database connection
测试数据库连接
ktx validate --connection warehouse
ktx validate --connection warehouse
Check logs
查看日志
cat .ktx/logs/latest.log
cat .ktx/logs/latest.log
Re-run setup to update credentials
重新运行setup更新凭证
ktx setup
ktx setup
Force re-ingestion with verbose output
强制重新导入并显示详细输出
ktx ingest --force --verbose
undefinedktx ingest --force --verbose
undefinedWorking with multiple environments
多环境使用
yaml
undefinedyaml
undefinedktx.yaml
ktx.yaml
databases:
prod:
type: postgres
host: "${PROD_DB_HOST}"
database: production
readOnly: true
staging:
type: postgres
host: "${STAGING_DB_HOST}"
database: staging
readOnly: true
```bashdatabases:
prod:
type: postgres
host: "${PROD_DB_HOST}"
database: production
readOnly: true
staging:
type: postgres
host: "${STAGING_DB_HOST}"
database: staging
readOnly: true
```bashIngest specific environment
导入指定环境
ktx ingest --connection prod
ktx ingest --connection staging
ktx ingest --connection prod
ktx ingest --connection staging
Search within specific connection
在指定连接内搜索
ktx sl "revenue" --connection prod
undefinedktx sl "revenue" --connection prod
undefinedTroubleshooting
故障排除
"LLM provider not configured"
"LLM provider not configured"
bash
undefinedbash
undefinedRe-run setup
重新运行setup
ktx setup
ktx setup
Or manually set in .ktx/env
或手动在.ktx/env中设置
echo "ANTHROPIC_API_KEY=sk-ant-..." >> .ktx/env
undefinedecho "ANTHROPIC_API_KEY=sk-ant-..." >> .ktx/env
undefined"Database connection failed"
"Database connection failed"
bash
undefinedbash
undefinedValidate connection details
验证连接详情
ktx validate --connection warehouse
ktx validate --connection warehouse
Check read-only user has SELECT permissions
检查只读用户是否有SELECT权限
Check network connectivity and firewall rules
检查网络连接和防火墙规则
Verify credentials in .ktx/env or environment
验证.ktx/env或环境中的凭证
undefinedundefined"Context ingestion failed"
"Context ingestion failed"
bash
undefinedbash
undefinedCheck specific error in logs
在日志中查看具体错误
cat .ktx/logs/latest.log
cat .ktx/logs/latest.log
Common issues:
常见问题:
- dbt artifacts not generated: run dbt compile && dbt docs generate
dbt compile && dbt docs generate- dbt产物未生成:运行dbt compile && dbt docs generate
dbt compile && dbt docs generate- Notion API key expired: regenerate in Notion integrations
- Notion API密钥过期:在Notion集成中重新生成
- Looker project path incorrect: verify path in ktx.yaml
- Looker项目路径错误:验证ktx.yaml中的路径
Force re-ingestion
强制重新导入
ktx ingest --force --verbose
undefinedktx ingest --force --verbose
undefined"MCP server not starting"
"MCP server not starting"
bash
undefinedbash
undefinedCheck if port is already in use
检查端口是否已被占用
ktx mcp status
ktx mcp status
Stop existing server
停止现有服务器
ktx mcp stop
ktx mcp stop
Start with explicit project directory
使用明确的项目目录启动
ktx mcp start --project-dir /full/path/to/project
ktx mcp start --project-dir /full/path/to/project
Check MCP logs
查看MCP日志
cat .ktx/logs/mcp-server.log
undefinedcat .ktx/logs/mcp-server.log
undefined"Semantic layer validation errors"
"Semantic layer validation errors"
bash
undefinedbash
undefinedValidate all definitions
验证所有定义
ktx sl validate
ktx sl validate
Common issues:
常见问题:
- Invalid YAML syntax: check indentation
- YAML语法无效:检查缩进
- Missing source references: ensure source exists in semantic-layer/
- 缺少源引用:确保源在semantic-layer/中存在
- Circular joins: review join graph in raw-sources/
- 循环关联:查看raw-sources/中的关联图
Fix and re-validate
修复后重新验证
ktx sl validate
ktx ingest --force
undefinedktx sl validate
ktx ingest --force
undefined"Agent can't find ktx tools"
"Agent can't find ktx tools"
bash
undefinedbash
undefinedEnsure MCP server is running
确保MCP服务器正在运行
ktx mcp status
ktx mcp status
Restart MCP server
重启MCP服务器
ktx mcp stop
ktx mcp start
ktx mcp stop
ktx mcp start
In Claude Code, verify MCP connection:
在Claude Code中验证MCP连接:
/mcp-servers should list ktx
/mcp-servers应列出ktx
In Cursor/OpenCode, check MCP settings
在Cursor/OpenCode中检查MCP设置
undefinedundefinedAdvanced Usage
高级用法
Custom LLM provider
自定义LLM提供商
yaml
undefinedyaml
undefinedktx.yaml
ktx.yaml
llmProvider: ai-gateway
llmConfig:
endpoint: "${AI_GATEWAY_ENDPOINT}"
apiKey: "${AI_GATEWAY_API_KEY}"
model: claude-3-5-sonnet-20241022
undefinedllmProvider: ai-gateway
llmConfig:
endpoint: "${AI_GATEWAY_ENDPOINT}"
apiKey: "${AI_GATEWAY_API_KEY}"
model: claude-3-5-sonnet-20241022
undefinedPython API for custom workflows
用于自定义工作流的Python API
python
undefinedpython
undefinedUse ktx semantic layer in Python
在Python中使用ktx语义层
from ktx_sl import SemanticLayer
sl = SemanticLayer.from_project_dir("./my-project")
from ktx_sl import SemanticLayer
sl = SemanticLayer.from_project_dir("./my-project")
Query metrics
查询指标
result = sl.query(
metrics=["revenue_total", "customers_count"],
dimensions=["date"],
filters={"date": {"gte": "2024-01-01"}},
granularity="month"
)
print(result.to_dataframe())
undefinedresult = sl.query(
metrics=["revenue_total", "customers_count"],
dimensions=["date"],
filters={"date": {"gte": "2024-01-01"}},
granularity="month"
)
print(result.to_dataframe())
undefinedCI/CD integration
CI/CD集成
bash
undefinedbash
undefinedValidate in CI
在CI中验证
ktx validate --strict
ktx validate --strict
Export semantic layer for documentation
导出语义层用于文档
ktx sl export --output ./docs/metrics.json
ktx sl export --output ./docs/metrics.json
Test queries against semantic layer
测试语义层查询
ktx sl validate --test-queries ./tests/queries.sql
undefinedktx sl validate --test-queries ./tests/queries.sql
undefined