sql-template-mcp
This server is an MCP tool for managing a reusable SQL template library, letting you save, search, retrieve, update, delete, and track usage of SQL templates backed by Supabase.
Save SQL templates: Persist generated SQL as reusable templates with metadata (title, category, scenario, SQL text, keywords, core tables, placeholders, execution flow, example case, verification status, source), including automatic embedding generation and similar-template duplicate checks.
Search templates: Use hybrid retrieval (semantic vector recall + keyword matching) to find reusable templates, sortable by similarity and usage count, with optional filters for document type, category, and verified-only results.
Semantic search: Perform natural-language / paraphrased queries using pgvector cosine similarity (NVIDIA embeddings) to find templates by business intent.
Get template details: Fetch the full content of a single template by its ID.
List templates: Overview the template library with optional filtering by category, document type, and verification status.
Update templates: Modify existing templates (e.g., correct SQL, mark as verified, add execution flow or example case) and refresh embeddings accordingly.
Delete templates: Remove wrong or outdated templates.
Record usage: Increment a template's usage count and refresh its last-used timestamp to improve retrieval ranking and assess template value.
Graceful degradation: If no NVIDIA API key is configured, semantic search services fall back to keyword-only retrieval without breaking core functionality.
Leverages NVIDIA's free embedding API (nv-embed-v1) to generate 2048-dimensional semantic vectors for SQL templates, enabling semantic search and similarity matching.
Provides a database backend for storing SQL templates, including schema management, vector storage for embeddings, and querying capabilities via Supabase API.
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., "@sql-template-mcp search for a SQL template to get customer orders"
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.
sql-template-mcp
将 ssrc-sql-generator 技能生成的 SQL 步骤沉淀为可检索复用的模板库,解决本地 .md 模板手动维护繁琐的问题。与 zhenyun-pangu-mcp(数据库实时能力)互补解耦:后者负责查询公司内部生产库(实时事实,依赖 Archery 登录态),本工具负责读写自有模板库(历史经验,Supabase / Postgres)。
本目录是 uvx 打包版:通过
uvx --from <本目录>直接运行,无需pip install或手动建虚拟环境。含[project.scripts]入口sql-template-mcp(由sql_template_mcp.server:main提供)。.env通过MCP_ENV_DIR指定位置(uvx 运行在缓存目录,__file__不指向本项目,见config.py)。
一、能力一览
工具 | 作用 |
| 将生成的 SQL 沉淀为模板(含相似去重检查,自动生成 embedding;支持 |
| 混合检索:语义向量召回 + 关键词匹配,按相似度/使用次数排序 |
| 纯语义召回,适合自然语言/口语化、同义改写查询 |
| 按 id 获取单个模板完整内容 |
| 总览模板库(可按分类/单据类型/验证状态过滤) |
| 更新已有模板(如补充 ✅ 已验证标记、修正 SQL,同步刷新 embedding) |
| 删除错误/过期模板 |
| 记录模板被使用一次(统计使用次数,优化检索排序) |
Related MCP server: mcp-codesearch
二、零基础傻瓜式安装(Mac)
本工具用 uv 管理 Python 环境。uv 会自动下载对应版本的 Python 并拉取依赖,本机可以没有预装 Python。下面每一步照抄执行即可。
2.1 安装 uv(同时自带 uvx)
打开「终端」(Finder → 应用程序 → 实用工具 → 终端),粘贴下面命令回车:
curl -LsSf https://astral.sh/uv/install.sh | sh(如果你装了 Homebrew,也可以用 brew install uv,二选一即可。)
脚本装完后,把 uv 加进 PATH:
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc
source ~/.zshrc2.2 验证 uv 是否装好
uv --version
uvx --version两条命令都能输出版本号(建议 uv >= 0.5)即成功。若提示 command not found,说明 PATH 没生效:重开一个终端窗口再试;或用绝对路径 ~/.local/bin/uv --version 确认。
2.3 安装 Python(可选但推荐)
uv 会自动下载所需 Python,这步可跳过。想提前手动装一份独立的 Python(不污染系统)就执行:
uv python install 3.112.4 拉取依赖(预热,首次必做)
uvx 首次运行要先解析并缓存依赖,耗时较久,可能让 MCP 客户端超时。先手动预热一次:
cd /你的路径/zhenyun-tools/sql-template-mcp
uv sync看到 Installed <数量> packages 字样即完成。
国内网络受限时可先设置镜像再执行上面的
uv sync:export UV_DEFAULT_INDEX=https://pypi.tuna.tsinghua.edu.cn/simple
2.5 配置 .env
在项目目录下,把模板复制成 .env:
cd /你的路径/zhenyun-tools/sql-template-mcp
cp .env.example .env用文本编辑器(VSCode / 文本编辑)打开 .env,填写:
SUPABASE_URL=https://your-project-ref.supabase.co
SUPABASE_SERVICE_ROLE_KEY=your-service-role-key
# 可选:语义检索。不填则自动降级为纯关键词检索
NVIDIA_API_KEY=SUPABASE_URL/SUPABASE_SERVICE_ROLE_KEY:Supabase 控制台 → Project Settings → API 中获取。NVIDIA_API_KEY:https://build.nvidia.com/nvidia/nv-embed-v1 免费申请,默认模型nvidia/nv-embed-v1(2048 维)。
Service Role Key 拥有绕过 RLS 的完整权限,仅限服务端/本地 MCP 使用,切勿暴露给前端或提交到仓库。
2.6 建表
在 Supabase 控制台 SQL Editor 中执行 schema.sql(幂等,可重复执行)。
2.7 写入种子模板 / 回填 embedding(可选)
# 种子模板(幂等,可重复执行)
uv run --directory "$DIR" python scripts/seed_data.py
# 仅在配置 NVIDIA_API_KEY、需要语义检索时回填 embedding
uv run --directory "$DIR" python scripts/backfill_embeddings.py2.8 注册为 MCP Server
在 MCP 客户端配置中加入(把 $DIR 替换成本目录绝对路径,例如 /你的路径/zhenyun-tools/sql-template-mcp):
{
"mcpServers": {
"sql-template": {
"command": "uvx",
"args": ["--from", "$DIR", "sql-template-mcp"],
"cwd": "$DIR",
"env": { "MCP_ENV_DIR": "$DIR" }
}
}
}要点:
必须使用绝对路径,不要用
~或相对路径。MCP_ENV_DIR指向包含.env的目录:uvx 运行在缓存目录,__file__不指向本项目,故.env需通过MCP_ENV_DIR显式指定(见config.py);不设置则回退到cwd目录的.env。凭据不写入客户端配置。
2.9 验证
# 连通 Supabase 并预览模板库前 5 条
uvx --from "$DIR" sqltpl该 MCP 提供 8 个工具,客户端显示 8 tools / 0 prompts 属正常。
三、零基础傻瓜式安装(Windows)
3.1 安装 uv(同时自带 uvx)
按 Win 键搜索「PowerShell」,右键 → 以管理员身份运行,粘贴下面命令回车:
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"(如果你装了 winget,也可以用 winget install --id=astral-sh.uv -e,二选一即可。)
3.2 验证 uv 是否装好
安装后重开一个 PowerShell 窗口(让 PATH 生效),再执行:
uv --version
uvx --version两条命令都能输出版本号(建议 uv >= 0.5)即成功。若提示无法识别,说明 PATH 没生效:重开窗口再试。
3.3 安装 Python(可选但推荐)
uv 会自动下载所需 Python,这步可跳过。想提前装就执行:
uv python install 3.113.4 拉取依赖(预热,首次必做)
在 PowerShell 中进入项目目录并预热:
cd C:\你的路径\zhenyun-tools\sql-template-mcp
uv sync看到 Installed <数量> packages 字样即完成。
国内网络受限时可先设置镜像再执行上面的
uv sync:$env:UV_DEFAULT_INDEX = "https://pypi.tuna.tsinghua.edu.cn/simple"
3.5 复制并填写配置文件
在 PowerShell 中复制模板:
Copy-Item .env.example .env用编辑器(VSCode / 记事本)打开 .env,按「2.5」一节的变量说明填写。
3.6 建表
在 Supabase 控制台 SQL Editor 中执行 schema.sql(幂等,可重复执行)。
3.7 写入种子模板 / 回填 embedding(可选)
uv run --directory "$DIR" python scripts/seed_data.py
uv run --directory "$DIR" python scripts/backfill_embeddings.py3.8 注册为 MCP Server
在 MCP 客户端配置中加入(把 $DIR 替换成本目录绝对路径,Windows 路径统一用正斜杠,例如 C:/你的路径/zhenyun-tools/sql-template-mcp):
{
"mcpServers": {
"sql-template": {
"command": "uvx",
"args": ["--from", "$DIR", "sql-template-mcp"],
"cwd": "$DIR",
"env": { "MCP_ENV_DIR": "$DIR" }
}
}
}若客户端找不到 uvx,用 where uvx 查出绝对路径,把 command 改成该路径。
3.9 验证
uvx --from "$DIR" sqltpl四、语义检索(向量)说明
采用混合检索:保留原有表存储(SQL 原文、元数据、统计、去重指纹),新增 embedding 向量列做语义召回。无需替换表,只是能力升级。
Embedding 模型:NVIDIA 免费 API
nvidia/nv-embed-v1(2048 维),免费 key 在 build.nvidia.com 申请。 因 2048 维超过 pgvector 的 HNSW/IVFFlat 索引维度上限 2000,当前 schema 不创建向量索引,语义检索走顺序扫描(模板库规模小,性能足够)。未配置
NVIDIA_API_KEY时:search_sql_template自动降级为纯关键词检索,不破坏原有能力。存量模板:表升级后
embedding列为空,需跑一次回填脚本(见上文 2.7)。
五、与 ssrc-sql-generator 的协作
生成 SQL 前:技能调用
search_sql_template(混合检索,含语义召回)或semantic_search_sql_template(自然语言查询)检索可复用模板(优先 ✅ 已验证);命中含execution_flow的模板时强制分步执行(逐 STEP QUERY + ASSERT),禁止直接输出最终 SQL。生成 SQL 后:技能询问用户是否
save_sql_template沉淀本次结果(自动写入 embedding;数据修复类同时沉淀execution_flow与example_case)。MCP / NVIDIA 不可用时:技能降级为「纯关键词检索 / 不检索直接生成、提示无法沉淀」,不阻塞主流程。
Available Tools
8 toolsdelete_sql_templateB
删除指定模板(清理错误/过期模板)。
Inputs: template_id (required). Returns: result
get_sql_templateA
按 id 获取单个模板的完整内容。
Inputs: template_id (required). Returns: result
list_sql_templatesA
列出模板库中的模板(可按分类/单据类型/验证状态过滤),用于总览。
Inputs: limit, category, doc_type, verified_only. Returns: result
record_template_usageA
记录某模板被实际使用一次(使用次数 +1,刷新最近使用时间)。
在技能复用模板生成最终 SQL 后调用,用于评估模板价值、优化检索排序。
Inputs: template_id (required). Returns: result
save_sql_templateA
将一次生成的 SQL 步骤沉淀为模板,存入模板库(Supabase)。
参数:
title: 模板标题(如「询价单回退至报价中」)
category: 业务分类,建议取值:通用基础查询 / 询价单RFX / 征询单RF / 数据修复
scenario: 业务场景描述(检索主要依据,请写清楚用途)
sql_text: 完整 SQL 文本(保留
{...}或<...>占位符原样)execution_flow: 执行过程伪代码(数据修复类模板强烈建议填写)。标准语法: [INPUT] <入参1>, <入参2> [STEP n: 步骤名] QUERY: 前置查询 SQL(用 {变量} 引用上一步提取的真实值) ASSERT: 断言(如「必须返回 1 行,提取 {tenant_id};0 行则终止报错」) CONDITION: 条件短路(如「IF {status} == 'X' THEN RETURN 无需修复」) ACTION: 修复语句(UPDATE/DELETE/INSERT,带乐观锁 object_version_number+1) 指导大模型分步调用 execute_sql,禁止跳过前置校验直接生成修复 SQL。
example_case: 脱敏示例(Few-Shot)。含:输入参数 → 各 STEP 中间结果 (如「Step 1 结果: tenant_id=155357」)→ 最终生成的可执行 SQL,消除大模型猜测。
doc_type: 单据类型(通用/询价单/招标单/征询单/数据修复)
keywords: 关键词/标签,逗号分隔(如「回退,报价中,延时消息」),用于检索
core_tables: 涉及核心表,逗号分隔(如「ssrc_rfx_header,spfm_pending_message」)
placeholders: 占位符清单,逗号分隔(如「tenant_id,rfx_header_id」)
verified: 是否「✅ 已验证」(验证过的模板可被技能免 MCP 校验复用)
verified_at: 验证日期(verified=True 时建议填写,如 2026-07-23)
template_no: 模板编号(如 2.6.6),便于与历史模板对应
created_by: 作者(为团队共享预留)
source: 来源标记(auto=技能自动沉淀 / migrated=手工迁移 / manual=手工新增)
skip_dup_check: 跳过相似去重检查直接写入
返回:保存结果(含模板 id)或相似模板提示。
Inputs: title (required), category (required), scenario (required), sql_text (required), +12 more. Returns: result
search_sql_templateA
在模板库中检索可复用的 SQL 模板(生成 SQL 前先调用,形成闭环)。
采用混合检索:语义向量召回(NVIDIA Embedding) + 关键词模糊匹配,按相似度/使用次数综合排序。 若未配置 NVIDIA_API_KEY,自动降级为纯关键词检索,不影响原有能力。
参数:
keyword: 关键词或自然语言描述(如「把询价单退回到报价中」「ssrc_rfx_header」)
doc_type: 按单据类型过滤(通用/询价单/招标单/征询单/数据修复)
category: 按业务分类过滤(通用基础查询/询价单RFX/征询单RF/数据修复)
verified_only: 仅返回「✅ 已验证」模板
limit: 返回条数上限
use_semantic: 是否启用语义召回(默认 true;无 NVIDIA key 时自动忽略)
返回:匹配模板的 Markdown 列表(含 SQL 与验证状态,语义命中会标注相似度)。
Inputs: limit, keyword, category, doc_type, +2 more. Returns: result
semantic_search_sql_templateA
用语义向量召回模板,适合自然语言/口语化描述(如同义改写、业务意图)。
底层调用 schema.sql 的 match_sql_templates RPC(pgvector 余弦距离)。 需配置 NVIDIA_API_KEY;未配置或调用失败时返回降级提示。
参数:
query: 自然语言查询(如「把询价单退回到报价中状态」「查某供应商名下所有在执行的招标单」)
doc_type: 按单据类型过滤(通用/询价单/招标单/征询单/数据修复)
category: 按业务分类过滤(通用基础查询/询价单RFX/征询单RF/数据修复)
verified_only: 仅返回「✅ 已验证」模板
threshold: 相似度阈值(0~1,越高越严格,默认 0.5)
limit: 返回条数上限
返回:按语义相似度排序的模板 Markdown 列表(含相似度分值)。
Inputs: query (required), limit, category, doc_type, +2 more. Returns: result
update_sql_templateB
更新已有模板的字段(如补充验证标记、修正 SQL、补充执行过程伪代码)。
execution_flow: 执行过程伪代码([INPUT]/[STEP]/QUERY/ASSERT/CONDITION/ACTION), 为存量高频数据修复模板渐进式补充,指导大模型分步执行。
example_case: 脱敏示例(输入参数 → 中间结果 → 最终 SQL 的完整轨迹)。
Inputs: template_id (required), title, category, doc_type, +10 more. Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 8 tools
The tools are mostly distinct: save/get/search/list/update/delete/record cover different CRUD and search operations. However, search_sql_template and semantic_search_sql_template overlap in purpose (both retrieve templates), though the descriptions clarify the semantic variant is for natural language queries. This slight overlap prevents a perfect score.
All tool names follow a consistent verb_noun pattern: save_sql_template, get_sql_template, search_sql_template, semantic_search_sql_template, list_sql_templates, update_sql_template, delete_sql_template, record_template_usage. The pattern is uniform and predictable, with clear verbs and the domain noun 'sql_template' (or plural in list).
With 8 tools, the server is well-scoped for a template management system. Each tool serves a distinct function: CRUD operations, two search modes, and usage tracking. This is within the ideal 3-15 range and feels complete without being bloated.
The tool surface covers the full lifecycle of SQL templates: create (save), read (get, search, list), update, delete, and usage tracking. The two search modes (keyword and semantic) address different retrieval needs. No obvious gaps exist for the stated purpose of managing a template library.
Maintenance
Related MCP Connectors
Text-to-SQL MCP server: read-only queries on PostgreSQL, MySQL and SQL Server with your real schema
Hosted SQL Server MCP server for Claude, ChatGPT and Cursor, with each action switched per account.
Related MCP Servers
- AlicenseAqualityDmaintenanceMCP server for semantic code search that indexes your codebase and allows AI editors to search using natural language queries.910 npm52MIT
- AlicenseAqualityBmaintenanceMCP server for semantic code search with AST-aware chunking, hybrid vectors, and query syntax.121Apache 2.0
- AlicenseNot gradedqualityDmaintenanceAn MCP server that provides SQL generation, validation, transpilation, and schema introspection across 10 SQL dialects, using a property graph schema and phase-locked reasoning to convert natural language to accurate SQL.3MIT
- AlicenseNot gradedqualityDmaintenanceAn MCP server for semantic code search using Qdrant vector database, enabling natural language queries to find relevant code snippets across indexed codebases.MIT