USQL MCP服务器

✨ 主要特点
- 🔌 通用数据库访问:查询PostgreSQL、MySQL、Oracle、SQLite、SQL Server和 100+其他数据库 通过单一界面
- ⚡ 后台执行:长时间运行的查询通过作业跟踪和轮询自动移动到后台
- 📊 进度报告:使用MCP进度通知对长期操作进行实时进度更新
- 🛡️ 查询安全:自动风险分析检测危险操作(DROP、不带WHERE的DELETE等)
- 📚 SQL工作流模板:常见任务(查询优化、数据分析、迁移)的内置提示
- 🗂️ 架构资源:通过MCP资源(数据库、表、列)浏览数据库模式
- ⚡ 演出:生产部署的模式缓存和速率限制
- 🔒 安全:凭证净化、可配置操作阻止、审核就绪错误消息
MCP能力
此服务器实现 所有4种MCP功能:
- 工具 (8个工具):执行查询、管理模式、检查作业状态
- 资源:通过浏览数据库元数据
sql://URI - 提示:用于常见任务的SQL工作流模板
- 进展:长时间运行操作的实时进度
需求
- Node.js 16或更新版本
npmusql已安装并可用于PATH
使用npx快速启动
直接通过npx运行服务器:
npx usql-mcp这将下载包并执行CLI入口点,该入口点在stdio上运行MCP服务器。
您还可以使用npm的Git支持直接从存储库运行它( prepare 脚本会自动编译TypeScript):
npx github:jvm/usql-mcp入门指南
git clone https://github.com/jvm/usql-mcp.git
cd usql-mcp
npm install
npm run build编译后的文件位于 dist/.他们故意不承诺--跑 npm run build 每当你需要新的输出时。
配置连接
通过环境变量定义连接字符串(USQL_*)或a config.json 文件镜像 config.example.json.每个 USQL_=... 条目将成为一个可重用的连接,其名称为小写 ` 部分(USQL_ORACLE1 → oracle1`).
环境变量
连接变量 (任何 USQL_* 以下保留密钥除外):
export USQL_POSTGRES="postgres://user:password@localhost:5432/mydb"
export USQL_SQLITE="sqlite:///$(pwd)/data/app.db"
export USQL_ORACLE1="oracle://user:secret@host1:1521/service"保留的配置变量:
USQL_CONFIG_PATH-config.json的路径USQL_QUERY_TIMEOUT_MS-默认查询超时(不设限制)USQL_DEFAULT_CONNECTION-从工具调用中省略时的默认连接名称USQL_BINARY_PATH-usql二进制文件的完整路径(如果不在path中)USQL_BACKGROUND_THRESHOLD_MS-后台执行阈值(默认值:30000)USQL_JOB_RESULT_TTL_MS-已完成的作业结果保留多长时间(默认值:3600000=1小时)
配置文件
创建 config.json 包含连接详细信息和服务器设置:
{
"connections": {
"postgres": {
"uri": "postgres://user:password@localhost:5432/mydb",
"description": "Production PostgreSQL database"
},
"sqlite": {
"uri": "sqlite:///path/to/database.db",
"description": "Local SQLite database"
}
},
"defaults": {
"defaultConnection": "postgres",
"queryTimeout": null,
"backgroundThresholdMs": 30000,
"jobResultTtlMs": 3600000,
"allowDestructiveOperations": true,
"blockHighRiskQueries": false,
"blockCriticalRiskQueries": false,
"requireWhereClauseForDelete": false,
"maxResultBytes": 10485760,
"rateLimitRpm": null,
"maxConcurrentRequests": 10,
"schemaCacheTtl": null
}
}配置选项:
queryTimeout:查询超时前的毫秒数(空=无限制)backgroundThresholdMs:超过此范围的查询将移至后台(默认值:30000)jobResultTtlMs:保留已完成作业结果的时间(默认值:3600000)allowDestructiveOperations:如果为false,则阻止DROP/TRUNCATE操作blockHighRiskQueries:阻止风险级别为“高”的查询blockCriticalRiskQueries:阻止风险级别为“严重”的查询requireWhereClauseForDelete:在DELETE/UPDATE上需要WHERE子句maxResultBytes:最大结果大小(以字节为单位)(默认值:10MB)rateLimitRpm:每分钟请求数限制(空=无限制)schemaCacheTtl:架构缓存TTL(毫秒)(null=无缓存)
客户端配置
本节介绍如何在不同的mcp客户端中配置usql-mcp服务器。
克劳德桌面版
Claude Desktop使用配置文件注册MCP服务器。位置取决于您的操作系统:
- macOS:
~/Library/Application Support/Claude/claude_desktop_config.json - 视窗:
%APPDATA%\Claude\claude_desktop_config.json - Linux:
~/.config/Claude/claude_desktop_config.json
将以下配置添加到您的 claude_desktop_config.json:
{
"mcpServers": {
"usql": {
"command": "npx",
"args": ["-y", "usql-mcp"],
"env": {
"USQL_DEFAULT_CONNECTION": "oracle://user:secret@host:1521/service",
"USQL_POSTGRES": "postgres://user:password@localhost:5432/mydb",
"USQL_SQLITE": "sqlite:///path/to/database.db"
}
}
}
}编辑配置文件后,重新启动Claude Desktop以使更改生效。
克劳德代码
Claude Code(CLI)通过其位于以下位置的配置文件支持MCP服务器:
- 所有平台:
~/.clauderc或~/.config/claude/config.json
将MCP服务器添加到您的Claude Code配置中:
{
"mcpServers": {
"usql": {
"command": "npx",
"args": ["-y", "usql-mcp"],
"env": {
"USQL_DEFAULT_CONNECTION": "oracle://user:secret@host:1521/service",
"USQL_POSTGRES": "postgres://user:password@localhost:5432/mydb",
"USQL_SQLITE": "sqlite:///path/to/database.db"
}
}
}
}服务器将在您的Claude Code会话中自动可用。
Codex CLI
Codex CLI配置因实现而异,但通常使用类似的JSON配置方法。创建或编辑Codex配置文件(通常 ~/.codexrc 或按照您的食品法典委员会文件中的规定):
{
"mcp": {
"servers": {
"usql": {
"command": "npx",
"args": ["-y", "usql-mcp"],
"env": {
"USQL_DEFAULT_CONNECTION": "oracle://user:secret@host:1521/service",
"USQL_POSTGRES": "postgres://user:password@localhost:5432/mydb",
"USQL_SQLITE": "sqlite:///path/to/database.db"
}
}
}
}
}有关确切的配置文件位置和格式,请参阅您的特定Codex CLI文档。
GitHub副本(VS代码)
VS Code中的GitHub Copilot可以通过Copilot Chat扩展设置使用MCP服务器。配置是通过VS代码完成的 settings.json:
- 通过以下方式打开VS代码设置(JSON):
- macOS: Cmd + Shift + P → “首选项:打开用户设置(JSON)” - Windows/Linux: Ctrl + Shift + P → “首选项:打开用户设置(JSON)”
- 添加MCP服务器配置:
{
"github.copilot.chat.mcp.servers": {
"usql": {
"command": "npx",
"args": ["-y", "usql-mcp"],
"env": {
"USQL_DEFAULT_CONNECTION": "oracle://user:secret@host:1521/service",
"USQL_POSTGRES": "postgres://user:password@localhost:5432/mydb",
"USQL_SQLITE": "sqlite:///path/to/database.db"
}
}
}
}保存设置后,重新加载VS Code或重新启动Copilot扩展以使更改生效。
环境变量与配置
对于所有客户,您可以选择:
- 内联环境变量 (如上所示)-配置文件中的连接字符串
- 系统环境变量 -设置
USQL_*shell配置文件中的变量
系统环境方法:
# In ~/.bashrc, ~/.zshrc, or equivalent
export USQL_DEFAULT_CONNECTION="oracle://user:secret@host:1521/service"
export USQL_POSTGRES="postgres://user:password@localhost:5432/mydb"
export USQL_SQLITE="sqlite:///path/to/database.db"然后使用更简单的客户端配置:
{
"mcpServers": {
"usql": {
"command": "npx",
"args": ["-y", "usql-mcp"]
}
}
}安全最佳实践
- 避免硬编码凭据:使用环境变量或安全凭据存储
- 文件权限:确保具有凭据的配置文件不是全球可读的(chmod 600)
- 只读访问:创建具有人工智能查询所需最低权限的数据库用户
- 网络安全:对远程数据库使用SSL/TLS连接
- 审计日志:启用数据库审计日志以跟踪AI生成的查询
- 查询安全:启用
blockCriticalRiskQueries防止破坏性操作 - 速率限制:设置
rateLimitRpm防止多用户环境中的滥用
工具目录
核心SQL工具
| 工具 | 目的 | 关键输入 | |
|---|---|---|---|
execute_query | 运行任意SQL语句 | connection_string, query,可选 output_format (json | csv), timeout_ms |
execute_script | 执行多语句脚本 | connection_string, script,可选 output_format, timeout_ms | |
list_databases | 列出服务器上可用的数据库 | connection_string,可选 output_format, timeout_ms | |
list_tables | 列出当前数据库中的表 | connection_string,可选 output_format, timeout_ms | |
describe_table | 通过以下方式检查表元数据 \d | connection_string, table,可选 output_format, timeout_ms |
后台作业管理
| 工具 | 目的 | 关键输入 |
|---|---|---|
get_job_status | 检查后台作业的状态 | job_id, wait_seconds (1-55) |
cancel_job | 取消正在运行的后台作业 | job_id |
服务器信息
| 工具 | 目的 | 关键输入 |
|---|---|---|
get_server_info | 获取服务器配置和统计信息 | 无(只读) |
资源
通过MCP资源访问数据库元数据:
sql://connections-列出所有可用连接sql://{connection}/databases-列出连接上的数据库sql://{connection}/{database}/tables-列出数据库中的表sql://{connection}/{database}/table/{name}-获取详细的表架构
示例用法:
Read resource: sql://postgres/production/tables
Read resource: sql://postgres/production/table/users提示
内置SQL工作流模板:
- 分析性能 -分析查询性能并提出优化建议
- 个人资料_数据_质量 -配置文件数据质量(零、重复、分布)
- 发电机迁移 -生成数据库迁移脚本
- 解释模式 -创建全面的模式文档
- optimize查询 -优化运行缓慢的查询
- debug_slow_query -系统地调试慢速查询
示例用法:
Use prompt: analyze_performance
connection: postgres
query: SELECT * FROM large_table WHERE status = 'active'后台执行
查询超过 backgroundThresholdMs (默认值:30秒)自动移动到后台执行:
- 初始响应:工具返回a
job_id和状态消息 - 轮询:使用
get_job_status随着wait_seconds检查进度 - 结果:完成后,
get_job_status返回完整结果 - 进展:运行作业的实时进度百分比(0-100)
- 清理:作业在之后会自动清理
jobResultTtlMs(默认值:1小时)
工作流程示例:
// Initial query (takes >30s)
execute_query → {
"status": "background",
"job_id": "abc-123",
"message": "Query is taking longer than 30000ms. Use get_job_status to check progress.",
"started_at": "2025-01-15T10:30:00Z"
}
// Check status (waits up to 10s)
get_job_status(job_id: "abc-123", wait_seconds: 10) → {
"status": "running",
"job_id": "abc-123",
"progress": 45, // 45% complete
"elapsed_ms": 15000
}
// Eventually completes
get_job_status(job_id: "abc-123", wait_seconds: 10) → {
"status": "completed",
"job_id": "abc-123",
"result": { "format": "json", "content": "[...]" },
"elapsed_ms": 45000
}查询安全分析
每个查询都会自动分析安全风险:
风险等级:
- 低:安全的只读查询
- 中等:使用WHERE子句修改操作
- 高:具有许多JOIN的复杂查询,缺少索引
- 关键的:破坏性操作(DROP、TRUNCATE、不带WHERE的DELETE)
响应包括分析:
{
"format": "json",
"content": "[...]",
"safety_analysis": {
"risk_level": "critical",
"warnings": ["DELETE operation without WHERE clause"],
"dangerous_operations": ["DELETE"],
"complexity_score": 2,
"recommendations": ["Add WHERE clause to limit deletion scope"]
}
}配置选项:
allowDestructiveOperations: false-阻止所有破坏性操作blockHighRiskQueries: true-阻止具有“高”风险的查询blockCriticalRiskQueries: true-阻止具有“严重”风险的查询requireWhereClauseForDelete: true-删除/更新时需要在哪里
响应格式
成功的调用返回由以下函数生成的确切stdout usql,与格式指示符配对:
{
"format": "json", // or "csv"
"content": "[{\"id\":1,\"name\":\"Alice\"}]",
"elapsed_ms": 234,
"safety_analysis": {
"risk_level": "low",
"warnings": [],
"dangerous_operations": [],
"complexity_score": 1,
"recommendations": []
}
}后台作业响应:
{
"status": "background",
"job_id": "uuid-string",
"message": "Query is taking longer than 30000ms. It will continue running in the background.",
"started_at": "2025-01-15T10:30:00.000Z",
"elapsed_ms": 30001
}如果 usql 如果以非零代码退出,处理程序将通过MCP错误形状转发消息,保留经过净化的连接字符串和原始stderr等详细信息。
性能特点
架构缓存
启用缓存以减少元数据查询的子流程开销:
{
"defaults": {
"schemaCacheTtl": 300000 // 5 minutes
}
}缓存操作:
list_databaseslist_tablesdescribe_table- 资源读取
缓存统计信息可通过 get_server_info:
{
"schema_cache_stats": {
"hits": 42,
"misses": 8,
"size": 15,
"hit_rate": 0.840
}
}速率限制
保护您的数据库免受滥用:
{
"defaults": {
"rateLimitRpm": 60, // 60 requests per minute
"maxConcurrentRequests": 10
}
}超过限制时:
{
"error": "RateLimitExceeded",
"message": "Rate limit exceeded: 60 requests per minute. Try again in 45 seconds.",
"details": {
"limit": 60,
"current": 60,
"resetInSeconds": 45
}
}发展
npm run dev–TypeScript在监视模式下编译npm run build–将ESM输出发送到dist/npm run lint–ESLint/Pretier规则npm run testJest单元测试(519个测试,全面覆盖)npm run type-check–严格tsc --noEmit
调试日志记录遵循中的命名空间 DEBUG=usql-mcp:*.
建筑
看 CLAUDE.md 用于编码代理指南和架构文档。
关键组件:
- 工具 (
src/tools/)-MCP工具实施 - 资源 (
src/resources/)-MCP资源处理程序 - 提示 (
src/prompts/)-SQL工作流模板 - 后台作业 (
src/usql/job-manager.ts)异步执行跟踪 - 查询安全 (
src/utils/query-safety-analyzer.ts)-风险分析 - 缓存 (
src/cache/schema-cache.ts)-性能优化 - 进展 (
src/notifications/progress-notifier.ts)-实时更新
测试
# Run all tests
npm test
# Run specific test file
npm test -- execute-query.test.ts
# Run with coverage
npm test -- --coverage
# Integration tests (require usql installed)
npm test -- integration测试覆盖率:
- 519项测试通过
- 所有工具、实用程序和管理器的单元测试
- 与真实SQLite数据库的集成测试
- 请求跟踪、分页和协议合规性测试
贡献
看 CONTRIBUTING.md 关于贡献者指南和 CLAUDE.md 编码剂指南。在做出重大更改之前打开一个问题,这样我们就可以保持工具的精简,并与MCP生态系统保持一致。
许可证
MIT许可证-请参阅 LICENSE 了解详情。
