sqlglot-mcp
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@sqlglot-mcpTrace column lineage for: SELECT id, SUM(amount) FROM orders GROUP BY id"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
sqlglot-mcp
基于 sqlglot 的 SQL 血缘分析 MCP 服务,通过 Model Context Protocol 暴露给 Claude Desktop / Cursor / 自研客户端等使用。
支持:
表级血缘: 识别写出语句(
SELECT/INSERT INTO ... SELECT/CREATE TABLE AS/MERGE/UPDATE)的目标表、物理来源表,以及中间表(CTE)的展开。列级血缘: 每个输出列追溯到物理来源列(含表达式变换,如
concat、sum、case when)。字段溯源: 输出"输出列 → 中间步骤(CTE/子查询)→ 物理来源列"的完整链路。
多方言: 工具参数
dialect自由指定(sqlglot 支持的二十七种以上方言,默认presto)。
快速开始
# 依赖 python >= 3.10
pip install -e .
# 启动(stdio 模式,MCP 客户端会自动拉起)
sqlglot-mcp也可以直接运行 python -m sqlglot_mcp。
若遇到 PEP 668(externally-managed-environment)报错,可加
--break-system-packages, 或使用 venv / uv / conda 环境。
Related MCP server: databricks-sql-mcp
MCP 客户端配置
Claude Desktop
claude_desktop_config.json:
{
"mcpServers": {
"sqlglot": {
"command": "/absolute/path/to/venv/bin/sqlglot-mcp",
"args": []
}
}
}Cursor
Settings → MCP → Add server,command 填 sqlglot-mcp(若在 venv 中,填 venv 下的可执行文件绝对路径)。
通用(自研 MCP 客户端)
{
"mcpServers": {
"sqlglot": {
"command": "sqlglot-mcp",
"args": []
}
}
}工具列表
工具 | 说明 |
| 分析 SQL 血缘,返回 JSON(表级 |
| 校验 SQL 可解析性,返回语句类型/目标表/来源表 |
| 列出当前环境支持的方言 |
schema 参数示例(可传对象或 JSON 字符串):
{"dim.user": ["id", "name", "org_id"], "dim.org": ["id", "name"]}当查询里出现未加表前缀的列(如 CTE 内部 SELECT id, org_name FROM ...),只要某列只存在于一张表,提供 schema 后即可精确溯源到物理表;同时存在于多张表的列会如实标记为 unknown_sources(不猜测)。
返回值示例
{
"ok": true,
"dialect": "presto",
"statement": "insert",
"target_table": "dws.user_daily",
"table_lineage": {
"target": "dws.user_daily",
"operation": "insert",
"sources": ["dim.user", "dim.region", "ods.orders"],
"intermediate_tables": [
{"name": "user_region", "type": "cte", "sources": ["dim.user", "dim.region"]},
{"name": "orders_agg", "type": "cte", "sources": ["ods.orders"]}
],
"edges": [
{"from": "dim.user", "to": "dws.user_daily"},
{"from": "dim.region", "to": "dws.user_daily"},
{"from": "ods.orders", "to": "dws.user_daily"}
]
},
"columns": [
{
"output_column": "total_amount",
"source_columns": [
{"table": "ods.orders", "column": "amount", "via": "o.amount", "qualified": "ods.orders.amount"}
],
"unknown_sources": 0,
"paths": [
[
{"node": "total_amount", "expr": "...", "is_source": false, "reference": null},
{"node": "oa.total_amount", "expr": "...", "is_source": false, "reference": "orders_agg"},
{"node": "o.amount", "expr": "ods.orders AS o", "is_source": true,
"table": "ods.orders", "source_column": "o.amount"}
]
]
}
],
"errors": []
}字段说明:
table_lineage.sources: 物理来源表(CTE 别名已被展开);intermediate_tables给出每个 CTE 的物理来源。columns[].source_columns: 输出列的直接来源列(table物理表,column裸列名,via是 SQL 中的写法,qualified为全限定名)。columns[].paths: 字段溯源链路,reference指向中间表/CTE 别名,is_source=true的节点为最终物理来源;unknown_sources表示无法追溯到具体列的来源(如count(*)、未提供 schema 的外部表)。errors: 某些列解析失败时的提示(单列失败不影响整体结果)。
开发
PYTHONPATH=src python3 -m unittest discover -s tests -v # 运行测试(核心逻辑 + MCP 协议集成)目录结构:
src/sqlglot_mcp/
├── lineage.py # 血缘分析核心(纯函数,可独立复用)
├── server.py # MCP 服务层(MCPServer, stdio)
└── __main__.py # python -m sqlglot_mcp 入口
tests/
├── test_lineage.py # 血缘逻辑单元测试
└── test_server.py # MCP stdio JSON-RPC 集成测试Available Tools
3 toolsanalyze_lineageA
分析 SQL 血缘。返回 JSON 字符串,包含表级依赖(table_lineage)与列级血缘(columns,含 source_columns 和 paths 溯源链路)。
Args: sql: 待分析的 SQL 语句(支持 SELECT / INSERT INTO ... SELECT / CREATE TABLE AS / MERGE 等)。 dialect: SQL 方言,默认 presto;可传 trino/spark/hive/mysql/postgres/clickhouse 等,详见 list_dialects。 with_full_trace: 是否在结果中包含每个输出列到来源列的完整溯源路径(full paths)。 schema: 可选的表结构 JSON,用于解析未限定/有歧义的列,如 {"dim.user": ["id", "name"], "dim.org": ["id"]}。
| Name | Required | Description | Default |
|---|---|---|---|
| sql | Yes | ||
| schema | No | ||
| dialect | No | presto | |
| with_full_trace | No |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
无注解提供,描述承担了行为披露的全部责任。它说明了返回 JSON 结构(table_lineage、columns、source_columns、paths),以及 with_full_trace 参数的作用,还描述了 schema 参数的用途。虽然没有提及错误行为、权限或副作用,但对于一个分析型工具,这些核心行为已充分披露。
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
描述长度适中,首句点明用途和输出,然后以 Args 部分逐一说明参数,结构清晰。每句话都有价值,没有冗余。虽然稍长,但均为必要信息。
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
对于 SQL 血缘分析这种复杂工具,描述涵盖了输出结构、参数语义、方言选项、schema 用途,并引用了 list_dialects。且存在输出 schema(has_output_schema=true),描述无需赘述返回格式细节。整体完整,代理无需额外信息即可正确调用。
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
schema 描述覆盖率为 0%,描述必须补偿。它解释了每个参数:sql 支持的类型、dialect 的默认值和可选项、with_full_trace 的含义、schema 的格式和用途。这些信息远超 schema 仅有的类型和默认值,极大帮助代理正确使用参数。
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
描述明确说明'分析 SQL 血缘'并详细说明返回内容(表级依赖和列级血缘),动词+资源明确,与兄弟工具(validate_sql、list_dialects)区分明显。虽然不是直接说'本工具用于血缘分析',但语义上清晰无误。
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
描述提到了支持的 SQL 类型和方言选项,并指引'详见 list_dialects'来获取方言详情,这提供了一些使用上下文。但没有明确说明何时使用本工具 vs validate_sql,也没有排除性说明,例如'如果需要验证 SQL 请使用 validate_sql'。因此指南部分仅属中等。
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
list_dialectsA
列出当前环境 sqlglot 支持的全部 SQL 方言。返回 JSON 数组。
| Name | Required | Description | Default |
|---|---|---|---|
No parameters | |||
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries the behavioral burden. It clearly states that the tool returns a JSON array Edition and uses the read-only verb 'list', implying no mutation. It could be more explicit about side effects or external dependencies, but for this simple introspection tool the return behavior is disclosed adequately.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is a single, efficient sentence that front-loads the action and resource before stating the return format. There is no redundant wording, and every phrase adds useful meaning.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a parameterless listing tool with an output schema already available, the description is complete. It states exactly what is listed, the scope ('current environment'), and the return format, leaving no essential information missing.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The tool has zero parameters)Skip, as shown by the empty input schema. The description correctly avoids adding parameter details. A zero-parameter tool gets a baseline score of 4 because there is no parameter semantic burden to satisfy.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description states a specific action ('list') and a clear resource: all SQL dialects supported by the current sqlglot environment. It is distinct from the sibling tools analyze_lineage and validate_sql, which clearly perform different operations.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description implies when to use the tool, but it does not explicitly state when to prefer it over alternatives or mention any exclusions. Since the sibling tools are unrelated in purpose, an agent can infer the appropriate context, but explicit routing guidance is absent.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
validate_sqlA
校验 SQL 可解析性并返回语句类型/目标表。返回 JSON。
Args: sql: 待校验的 SQL。 dialect: SQL 方言,默认 presto。
| Name | Required | Description | Default |
|---|---|---|---|
| sql | Yes | ||
| dialect | No | presto |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
没有 annotations,描述承担了行为披露的主要责任。它说明了返回 JSON 和返回的字段类型,且“校验可解析性”暗示该操作不会执行 SQL 或产生副作用;但未说明错误处理方式、方言不受支持时的行为、是否只校验单条语句等。
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
描述非常简短,先给出用途摘要,再用参数列表说明输入,结构清晰且没有冗余内容。“返回 JSON”一句虽然能从输出 schema 推断,但作为快速提示成本很低。
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
对于只有两个参数且存在输出 schema 的工具,描述基本覆盖了调用所需的信息:做什么、返回什么、参数含义和默认值。但缺少与同级工具的边界说明、方言取值范围、错误行为或更细的使用场景,完整性仍有提升空间。
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema 中两个参数均无描述(coverage 0%),描述用简短的 Args 部分为 sql 和 dialect 补充了含义,并明确 dialect 默认值为 presto。虽然没有列出合法的方言值,但已经为每个参数提供了基本语义,显著弥补了 schema 的空白。
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
描述用具体动词“校验”和资源“SQL”说明了核心功能,并给出返回内容(语句类型/目标表),让代理清楚这是解析性检查工具。虽然没有点名区别于 analyze_lineage/list_dialects,但“校验可解析性”这一用途本身已足以与血统分析和方言列表区分。
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
描述隐含地表明该工具用于校验 SQL 可解析性并获取语句类型和目标表,但没有明确说明何时优先于 analyze_lineage/list_dialects,也没有提供排除情形或备选工具指引。使用场景只能由代理自行推断。
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
3 tool updates
v0.1.0- First observed
analyze_lineage - First observed
list_dialects - First observed
validate_sql
TDQS
Scored across 3 tools
Each tool has a clearly distinct purpose: analyze_lineage performs dependency analysis, validate_sql checks parseability and metadata, and list_dialects enumerates supported dialects. While validate_sql and analyze_lineage both accept SQL input, their outputs and intents are unambiguous.
All tool names follow a clean snake_case verb_noun pattern: analyze_lineage, validate_sql, list_dialects. The naming is consistent, descriptive, and predictable.
Three tools is within the well-scoped range for a focused SQL analysis server. Each tool earns its place: one for lineage, one for validation, and one to support dialect discovery.
The set covers lineage analysis and validation, but for a server named sqlglot-mcp there are notable gaps: no transpilation, formatting, or general AST/parse tools. The core lineage workflow is usable, but the surface feels incomplete relative to SQLGlot's broader capabilities.
Maintenance
Related MCP Connectors
The grounded data layer for any LLM: governed SQL, metrics, lineage and catalog over your data.
Generate, edit, and export data-architecture diagrams from your AI. Column lineage, PNG in chat.
- AvoOAuthio.github.avohq
Define, ship & query your analytics tracking from one source of truth, trusted by humans and agents.
Cross-tool context for your data stack. Search, lineage, and impact across warehouse and BI tools.
Related MCP Servers
- AlicenseAqualityDmaintenanceProvides SQL analysis, linting, and dialect conversion using SQLGlot, enabling validation, transpilation, and extraction of table/column references.432MIT
- AlicenseNot gradedqualityDmaintenanceEnables AI assistants to execute SQL queries and explore databases, tables, and catalogs on Databricks using Unity Catalog.1MIT
- AlicenseNot gradedqualityCmaintenanceEnables AI agents to search, explore data lineage, understand business context, and generate SQL queries across an organization's data ecosystem.Apache 2.0
- AlicenseNot gradedqualityDmaintenanceEnables SQL agents to connect to any SQLAlchemy-supported database via MCP, providing read-only SQL querying, automatic table summarization, and column content search.4Apache 2.0