数据库模式搜索服务

提供数据库模式的全文搜索、语义搜索和模式检索功能,适用于数据库文档管理和数据分析场景。

  • by nstjuliana
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 nstjuliana/Company-MCP

使用说明

数据库上下文MCP服务器

提供以下功能的FastMCP服务器 数据库模式上下文 通过搜索和元数据工具。此MCP提供预索引数据库文档——它确实 不 连接到实际的数据库。

目的

该服务器从JSON/PMarkdown文件中索引数据库模式(表、列、关系),并提供:

  • FTS5全文搜索:BM25排名关键字搜索
  • 向量相似性搜索:使用OpenAI嵌入的语义搜索
  • 模式检索:从索引的JSON文件中获取表/列定义
  • 关系发现:查找表之间的连接路径

数据结构

目录布局

data/
├── index/
│   └── index.db              # SQLite index with FTS5 + vector search
└── map/
    ├── postgres_production/
    │   └── domains/
    │       ├── authentication/
    │       │   └── tables/
    │       │       ├── auth.users.json
    │       │       ├── auth.users.md
    │       │       ├── auth.sessions.json
    │       │       └── ...
    │       ├── payments/
    │       │   └── tables/
    │       │       ├── public.payments.json
    │       │       ├── public.merchants.json
    │       │       └── ...
    │       ├── realtime/
    │       ├── security/
    │       └── storage/
    └── snowflake_production/
        └── domains/
            ├── payments/
            │   └── tables/
            │       └── PUBLIC.DABSTEP_PAYMENTS.json
            └── workflow/
                └── tables/
                    ├── PUBLIC.DABSTEP_TASKS.json
                    ├── PUBLIC.DABSTEP_SUBMISSIONS.json
                    └── PUBLIC.DABSTEP_TASK_SCORES.json

JSON模式文件格式

每个表都记录在具有以下结构的JSON文件中:

{
  "table": "payments",
  "schema": "public",
  "database": "postgres_production",
  "description": "Payment transactions processed through the system...",
  "row_count": 138236,
  "columns": [
    {
      "name": "payment_id",
      "type": "character varying",
      "nullable": false,
      "description": "Unique identifier for each payment transaction..."
    }
  ],
  "primary_key": ["payment_id"],
  "foreign_keys": [],
  "indexes": [
    {
      "index_name": "payments_pkey",
      "columns": ["payment_id"],
      "is_unique": true
    }
  ]
}

索引数据库架构

SQLite索引数据库(data/index/index.db)包含以下表格:

documents --主要文件索引

存储所有索引内容(表和列)。

列 类型 描述
id INTEGER 主键
doc_type 文本 'table' 或 'column'
database_name 文本 'postgres_production' 或 'snowflake_production'
schema_name TEXT 模式(例如。, 'auth', 'public', 'PUBLIC')
table_name TEXT 表名
column_name TEXT 列名(用于列文档)
domain TEXT 业务领域类别
content TEXT 完整的JSON/Markdown内容
summary TEXT 生成的摘要
keywords TEXT JSON关键字数组
file_path TEXT 中源文件的路径 data/map/
content_hash TEXT SHA256用于变化检测
indexed_at 日期时间 索引时
parent_doc_id INTEGER FK到父级(用于列)

documents_fts --FTS5全文搜索

BM25排名文本搜索的虚拟表。

CREATE VIRTUAL TABLE documents_fts USING fts5(
    content, summary, keywords,
    content='documents', content_rowid='id'
);

documents_vec --矢量嵌入

用于语义相似性搜索的虚拟表(需要sqlite-vec扩展)。

CREATE VIRTUAL TABLE documents_vec USING vec0(
    document_id INTEGER PRIMARY KEY,
    embedding float[1536]  -- OpenAI text-embedding-3-small
);

keywords --提取的搜索词

带有频率计数的缓存关键字。

列 类型 描述
id INTEGER 主键
term 文本 关键字
source_type 文本 'table' 或 'column'
frequency 整数 发生次数

index_weights --搜索排名配置

doc_type fts_weight vec_weight boost
表 1.0 1.0 1.5
列 0.8 0.8 1.0
关系 1.0 1.0 1.2

index_metadata --索引配置

元数据的键值存储,如 embedding_model, embedding_dimensions, document_count, last_full_index.


快速开始

1.安装依赖项

pip install -r requirements.txt

2.设置环境(可选,用于矢量搜索)

创建 .env 使用您的OpenAI API密钥文件:

OPENAI_API_KEY=sk-your-api-key-here

3.初始化数据库

python setup_db.py

这创造了 data/index/index.db 与:

  • FTS5全文搜索索引
  • 用于语义搜索的向量嵌入(如果提供了OpenAI密钥)
  • 预先计算的关键字

4.运行服务器

python server.py

或者使用Docker:

docker build -t db-context-mcp .
docker run -p 8000:8000 --env-file .env db-context-mcp

MCP端点服务于 http://localhost:8000/mcp.

5.使用Python客户端进行测试

python client.py

Docker编写部署

对于完整部署 MCP服务器 和 SFTP服务器:

Docker Compose快速入门

# 1. Copy environment template
cp .env.example .env

# 2. Edit .env with your configuration
#    - Set a secure SFTP_PASSWORD
#    - Add OPENAI_API_KEY for vector search

# 3. Start all services
docker-compose up -d

服务

服务 端口 描述
MCP服务器 8000 数据库上下文MCP端点
SFTP服务器 2222 SFTP访问 /data 目录

SFTP访问

连接到SFTP服务器以进行程序化文件访问:

# Connect via SFTP
sftp -P 2222 datauser@localhost

# Default credentials (change in .env):
# User: datauser
# Password: changeme

文件可在以下网址访问 /home/datauser/data/ 哪个映射到 ./data 目录。

环境变量

变量 默认值 描述
MCP_PORT 8000 MCP服务器HTTP端口
OPENAI_API_KEY - 用于矢量搜索的OpenAI API键
SFTP_PORT 2222 SFTP服务器端口
SFTP_USER datauser SFTP用户名
SFTP_PASSWORD changeme SFTP密码

Docker命令

# Start all services
docker-compose up -d

# View logs
docker-compose logs -f

# Stop all services
docker-compose down

# Rebuild after changes
docker-compose up -d --build

# View service status
docker-compose ps

可用工具(共14个)

发现工具

工具 说明
list_databases 列出所有带有表计数和模式的索引数据库
list_domains 列出所有具有表计数的业务域
list_tables 列出所有表,可选择按数据库/域筛选

list_databases

了解索引中可用的数据库。

list_databases()

退货:

{
  "databases": [
    {"name": "postgres_production", "table_count": 37, "domains": [...], "schemas": [...]},
    {"name": "snowflake_production", "table_count": 4, "domains": [...], "schemas": [...]}
  ]
}

list_domains

列出所有具有表计数的业务域。

list_domains(
    database: str = ""    # Optional: filter by database
)

退货: {domains: [{name, description, table_count, databases}]}

list_tables

列出带有元数据的可用表。

list_tables(
    database: str = "",   # Optional: filter by database
    domain: str = ""      # Optional: filter by domain
)

退货: 列表 {name, title, database, schema, domain, summary, file_path}


搜索工具

工具 说明
search_fts FTS5全文搜索,BM25排名
search_vector 基于OpenAI嵌入的语义向量搜索
search_db_map 基于令牌的索引表快速搜索
search_tables 查找与自然语言查询匹配的表

search_fts

使用SQLite FTS5进行全文搜索,BM25排名。

search_fts(
    query: str,           # Search text (supports AND, OR, NOT, "exact phrase")
    database: str = "",   # Optional: filter by database
    domain: str = "",     # Optional: filter by domain
    doc_type: str = "",   # Optional: filter by type ("table" or "column")
    limit: int = 10       # Max results (1-50)
)

退货: 结果与 id, table_name, summary, file_path, bm25_rank

search_vector

使用OpenAI嵌入的语义搜索。查找具有相似含义的文档。

search_vector(
    query: str,           # Natural language query
    database: str = "",   # Optional: filter by database
    domain: str = "",     # Optional: filter by domain
    doc_type: str = "",   # Optional: filter by type
    limit: int = 10       # Max results (1-50)
)

退货: 结果与 id, table_name, summary, file_path, distance

注: 需要 OPENAI_API_KEY 环境变量。

search_db_map

对内存表索引进行基于令牌的快速搜索。

search_db_map(
    query: str,           # Free-text search string
    top_k: int = 3        # Number of results
)

退货: 列表 {id, title, score, snippet}

search_tables

使用标记重叠匹配查找与查询相关的表。

search_tables(
    query: str,           # Search text
    database: str = "",   # Optional: filter by database
    domain: str = "",     # Optional: filter by domain
    limit: int = 5        # Max results (1-20)
)

退货: {tables: [...], total_matches, tokens_used}


架构工具

工具 说明
list_columns 获取特定表的列
get_table_schema 从JSON文件获取完整的模式详细信息
get_domain_overview 获取域中的所有表

list_columns

获取表的列定义。

list_columns(
    table: str,           # Table name (e.g., "merchants", "DABSTEP_PAYMENTS")
    database: str = ""    # Optional: filter by database
)

退货: {table, columns: [{name, type, nullable, description}], file_path}

get_table_schema

从源JSON文件中检索完整的模式详细信息。

get_table_schema(
    table: str,                    # Table name
    database: str = "",            # Optional: filter by database
    include_samples: bool = False  # Include sample values if available
)

退货: 完整的架构包括:

  • name, database, schema, description
  • columns 带有类型和描述
  • primary_key, foreign_keys, indexes
  • related_tables, file_path

get_domain_overview

获取业务域中所有表的摘要。

get_domain_overview(
    domain: str,          # Domain name (e.g., "payments", "authentication")
    database: str = ""    # Optional: filter by database
)

退货: {domain, description, databases, tables: [{name, description}]}


关系工具

工具 说明
get_join_path 查找两个表之间的连接路径
get_common_relationships 列出基于FK的连接模式

get_join_path

通过外键遍历找到两个表之间的连接路径。

get_join_path(
    source_table: str,    # Starting table
    target_table: str,    # Target table
    database: str = "",   # Optional: filter by database
    max_hops: int = 3     # Maximum join hops
)

退货: {source, target, found, hop_count, path: [...], sql_snippet}

get_common_relationships

根据外键列出常用的连接模式。

get_common_relationships(
    database: str = "",   # Optional: filter by database
    domain: str = "",     # Optional: filter by domain
    limit: int = 10       # Max relationships
)

退货: {relationships: [{source_table, target_table, join_sql, description}]}


实用工具

工具 说明
add(a, b) 返回a+b(连接测试)
echo(message) 返回消息(连接测试)

示例用法

发现可用数据

# List all databases
list_databases()
# → postgres_production (37 tables), snowflake_production (4 tables)

# List tables in a specific database
list_tables(database="snowflake_production")

# List business domains
list_domains()

搜索表格

# FTS5 search
search_fts(query="payment fraud", limit=5)

# Semantic search
search_vector(query="tables related to financial transactions", limit=3)

# Search within a specific database
search_fts(query="merchant", database="postgres_production")

获取架构详细信息

# Get schema for a table (auto-detects database)
get_table_schema(table="payments")

# Get schema from specific database
get_table_schema(table="payments", database="postgres_production")
get_table_schema(table="DABSTEP_PAYMENTS", database="snowflake_production")

# Get columns only
list_columns(table="merchants", database="postgres_production")

探索关系

# Find join path between tables
get_join_path(
    source_table="merchants",
    target_table="payments",
    database="postgres_production"
)

# Get common relationships in a domain
get_common_relationships(domain="payments")

建筑

┌─────────────────────────────────────────────────────────────┐
│                     MCP Client                              │
└─────────────────────────────────────────────────────────────┘
                            │
                            ▼
┌─────────────────────────────────────────────────────────────┐
│                   FastMCP Server                            │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────────────┐ │
│  │ search_fts  │  │search_vector│  │ Schema Tools        │ │
│  └──────┬──────┘  └──────┬──────┘  └──────────┬──────────┘ │
│         │                │                     │            │
│         ▼                ▼                     ▼            │
│  ┌─────────────────────────────┐    ┌─────────────────────┐│
│  │   data/index/index.db      │    │   data/map/*.json   ││
│  │  ┌───────────┐ ┌─────────┐ │    │   (source schemas)  ││
│  │  │   FTS5    │ │ Vectors │ │    └─────────────────────┘│
│  │  └───────────┘ └─────────┘ │                            │
│  └─────────────────────────────┘                            │
└─────────────────────────────────────────────────────────────┘
                            │
                            ▼ (vector search only)
                   ┌────────────────┐
                   │  OpenAI API    │
                   │  (embeddings)  │
                   └────────────────┘

索引内容摘要

数据库 表 域 架构
postgres-production 37 分析、身份验证、客户、通用、消息传递、支付 身份验证、公共、实时、存储、保险库
雪花_生产 4 一般,付款 公共

总计: 41个表格,428个索引文档(表格+列)


备注

  • 没有数据库连接:此MCP仅提供预索引上下文,它不连接到实际的Postgres或Snowflake数据库。
  • 矢量搜索 需要 OPENAI_API_KEY 在运行时生成查询嵌入。
  • FTS5搜索 在没有OpenAI的情况下,使用预构建的索引即可工作。
  • 数据库参数:使用 database="postgres_production" 或 database="snowflake_production" 当表名可能重叠时,以特定数据库为目标。
  • 跑 setup_db.py 在将新的JSON文件添加到 data/map/ 重建索引。