sqlmcp

package module
v0.1.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 11, 2026 License: MIT Imports: 0 Imported by: 0

README

SQL MCP Server

面向 AI agent 的受控 SQL 数据访问网关。通过实体模型、关系代数 IR 与参数化 codegen 暴露 PostgreSQL、MySQL、OceanBase——不接受任意 SQL,不提供 DDL。

设计参考 Microsoft Data API Builder 的 MCP 思路,并在成本闸门、多租户预算与 fail-closed 安全边界上做了强化。详见 架构。

为什么选择

诉求 做法
防止 agent 随意查库 仅暴露配置中的实体与字段;值参数化,标识符来自元数据
防止误删/全表扫 写保护、EXPLAIN 预筛、确定性行数/字节上限、查询超时
多团队/多角色 RBAC、字段 ACL、行级策略、字段脱敏、按 session 预算
可运维 配置热重载、异步审计、OpenTelemetry hook、分层测试

安全行为与 provider 差异以 安全模型 为准,不以本页为准; 威胁、控制、验证证据与剩余风险见 威胁模型。

功能概览

MCP 面 — stdio 与 streamable HTTP;实体工具(describe / read / create / update / delete / execute / aggregate)与显式事务(begin / commit / rollback); 授权 schema resource;safe_read、safe_aggregate、rewrite_query prompts。

治理 — 参数化 SQL;RBAC + 字段 ACL + 行级策略 + mask;不可关闭的 Safety/Enforcement 成本链;模板 fingerprint 与读取反馈;角色/租户进程内预算。

数据 — 命名多数据源;同源关系展开;offset / keyset 分页;prepared statement 缓存。

快速开始

Docker(推荐): 只需 Docker 与 Docker Compose,即可启动 PostgreSQL 示例、 执行授权读取并观察全表读取/越权字段被拒绝:

docker compose -f examples/quickstart/compose.yaml up -d --wait
curl -fsS http://127.0.0.1:8080/healthz

完整的 Inspector 调用、tenant 隔离和拒绝示例见 5 分钟快速体验。

源码构建: 要求 Go 1.25.12+ 和一个 已验证数据库版本。

git clone https://github.com/nethinwei/sql-mcp-server.git
cd sql-mcp-server
make build

初始化配置、注入 DSN、校验并启动(stdio,适合本机 MCP 客户端):

sql-mcp-server init --config config.yaml --driver postgres
# 编辑 config.yaml,设置 dsn(可用 ${ENV} 占位符)
sql-mcp-server validate --config config.yaml
sql-mcp-server serve --config config.yaml --transport stdio --role reader

HTTP(开发时建议绑定 loopback):

sql-mcp-server serve --config config.yaml --transport http --addr 127.0.0.1:8080

完整配置示例见 examples/config.example.yaml。 运行细节、热重载与 secret 见 运行与 CLI。

注意: 默认 HTTP 地址 :8080 监听所有接口。非 loopback 且未配置 bearer token 或 mTLS 时,服务会 fail closed 并拒绝启动。

连接 MCP 客户端

stdio(Cursor、Claude Desktop、VS Code):在 MCP 配置中指定发布二进制路径 与 serve 参数;可复制 examples/clients/ 中的模板。

HTTP:端点为 /mcp;可用 MCP Inspector 探测:

npx -y @modelcontextprotocol/inspector http://127.0.0.1:8080/mcp

魔搭 ModelScope:使用根目录 mcp_config.json 进行 “仅本地可用/分发展示”配置;提交资料、Docker 方式和安全边界见 魔搭上架与使用。

文档

主题 链接
配置 configuration.md
安全边界 security.md · threat-model.md · SECURITY.md
运行与升级 operations.md
架构 architecture.md
不变量 invariants.md
测试与 CI testing.md
5 分钟体验 quickstart.md
魔搭 ModelScope modelscope.md
Provider 兼容性 provider-compatibility.md
Provider 路线图 provider-roadmap.md
支持版本 supported-versions.md
变更记录 CHANGELOG.md
发布说明 docs/releases/
路线图 roadmap.md
参与贡献 CONTRIBUTING.md

版本与迁移说明见 CHANGELOG 及各 发布说明; 未发布规划见 roadmap。

安全

如发现漏洞,请参阅 SECURITY.md。部署前请阅读 安全模型 中的信任边界与已知限制;安全分析与证据状态见 威胁模型。

许可

MIT

Documentation

Overview

Package sqlmcp provides a SQL MCP server: a relationally complete data access surface for AI agents over PostgreSQL, MySQL, and OceanBase, modeled on Microsoft's Data API Builder SQL MCP Server.

Design pillars:

  • Relational algebra IR (core/relalg + core/codegen) — dialect-neutral, mathematically complete; new databases plug in through core/provider.
  • Defense-in-depth cost & resource gate — EXPLAIN is one optional layer, not a leash; deterministic LIMIT/timeout and DB-native resource limits backstop unreliable estimates.
  • Enterprise safety — RBAC with row-level security, non-blocking audit, and field masking.
  • Bounded concurrency with backpressure — no unbounded goroutines.

The core packages depend only on the standard library. External dependencies (the MCP SDK, database drivers, OpenTelemetry, YAML) live under x/ and depend on core, never the reverse. See CONTRIBUTING.md for the coding standard.

Directories

Path Synopsis
cmd
sql-mcp-server command
Command sql-mcp-server is the entry point.
Command sql-mcp-server is the entry point.
core
audit
Package audit defines a best-effort, non-blocking audit sink.
Package audit defines a best-effort, non-blocking audit sink.
budget
Package budget provides role/tenant scoped execution budgets.
Package budget provides role/tenant scoped execution budgets.
cache
Package cache defines a generic read-result cache with per-table invalidation.
Package cache defines a generic read-result cache with per-table invalidation.
codegen
Package codegen renders a relalg.Expr (logical plan) into dialect-specific, fully parameterized SQL.
Package codegen renders a relalg.Expr (logical plan) into dialect-specific, fully parameterized SQL.
config
Package config defines the runtime configuration model: database, entities, per-tool toggles, cost thresholds, cache, rate limits, and audit.
Package config defines the runtime configuration model: database, entities, per-tool toggles, cost thresholds, cache, rate limits, and audit.
cost
Package cost implements the defense-in-depth cost & resource gate.
Package cost implements the defense-in-depth cost & resource gate.
dialect
Package dialect abstracts SQL dialect differences: identifier quoting, parameter placeholders, EXPLAIN wrapping, and capability negotiation.
Package dialect abstracts SQL dialect differences: identifier quoting, parameter placeholders, EXPLAIN wrapping, and capability negotiation.
engine
Package engine enforces bounded concurrency with backpressure, request deduplication (singleflight), and integration with adaptive limiting and the circuit breaker.
Package engine enforces bounded concurrency with backpressure, request deduplication (singleflight), and integration with adaptive limiting and the circuit breaker.
entity
Package entity defines the entity abstraction layer: configured tables, views, and procedures exposed to MCP tools, with aliases, field projection, masking, descriptions, role permissions, row-level security, and keys.
Package entity defines the entity abstraction layer: configured tables, views, and procedures exposed to MCP tools, with aliases, field projection, masking, descriptions, role permissions, row-level security, and keys.
hook
Package hook defines nil-safe lifecycle callbacks for observability.
Package hook defines nil-safe lifecycle callbacks for observability.
introspect
Package introspect defines schema introspection: discovering entity metadata from a live database, and detecting drift between configured and discovered schemas.
Package introspect defines schema introspection: discovering entity metadata from a live database, and detecting drift between configured and discovered schemas.
mask
Package mask defines field masking for sensitive data.
Package mask defines field masking for sensitive data.
provider
Package provider defines the database adapter contract consumed by the application assembly layer.
Package provider defines the database adapter contract consumed by the application assembly layer.
ratelimit
Package ratelimit provides adaptive concurrency control (AIMD) and a circuit breaker.
Package ratelimit provides adaptive concurrency control (AIMD) and a circuit breaker.
rbac
Package rbac defines authorization with row-level security.
Package rbac defines authorization with row-level security.
relalg
Package relalg defines a dialect-neutral relational algebra intermediate representation (IR).
Package relalg defines a dialect-neutral relational algebra intermediate representation (IR).
store
Package store defines the database execution abstraction used by core tools.
Package store defines the database execution abstraction used by core tools.
tool
Package tool defines the DML tool components and their registry.
Package tool defines the DML tool components and their registry.
internal
coveragecheck command
fmtcheck command
modelscopesmoke command
quickstartsmoke command
testdialect
Package testdialect provides dialect implementations for core package tests.
Package testdialect provides dialect implementations for core package tests.
Package version exposes build metadata shared by every server surface.
Package version exposes build metadata shared by every server surface.
x
bootstrap
Package bootstrap loads configuration and assembles the application: it resolves secret placeholders, opens the database provider, converts config entities to the core entity model, and wires the registry, authorizer, cost gate, engine, and tools.
Package bootstrap loads configuration and assembles the application: it resolves secret placeholders, opens the database provider, converts config entities to the core entity model, and wires the registry, authorizer, cost gate, engine, and tools.
configyaml
Package configyaml decodes YAML runtime configuration.
Package configyaml decodes YAML runtime configuration.
mcpserver
Package mcpserver bridges core DML tools to the MCP go-sdk.
Package mcpserver bridges core DML tools to the MCP go-sdk.
otel
Package otel adapts the core hook.Hooks callbacks to OpenTelemetry spans and attributes.
Package otel adapts the core hook.Hooks callbacks to OpenTelemetry spans and attributes.
providerregistry
Package providerregistry maps database driver names to provider factories.
Package providerregistry maps database driver names to provider factories.
providers/all
Package all registers every database provider built into the server binary.
Package all registers every database provider built into the server binary.
providers/mysql
Package mysql adapts a MySQL database to the core interfaces.
Package mysql adapts a MySQL database to the core interfaces.
providers/oceanbase
Package oceanbase adapts an OceanBase database (MySQL protocol) to the core interfaces.
Package oceanbase adapts an OceanBase database (MySQL protocol) to the core interfaces.
providers/postgres
Package postgres adapts a PostgreSQL database to the core interfaces: store.DB/Tx, dialect.Dialect, cost.Explainer, and introspect.Introspector.
Package postgres adapts a PostgreSQL database to the core interfaces: store.DB/Tx, dialect.Dialect, cost.Explainer, and introspect.Introspector.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL