sqlmcp

package module
v0.1.11 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2026 License: MIT Imports: 0 Imported by: 0

README

SQL MCP Server

The governed SQL gateway for untrusted AI agents.

面向不可信 AI Agent 的受控 SQL 数据访问网关。通过显式 Entity、关系代数 IR 和 参数化 codegen 访问 PostgreSQL、MySQL 与 OceanBase,不接受任意 SQL,不提供 DDL。

核心差异

  • 确定性执行:Agent 只能组合受控工具和白名单 IR;
  • 字段与行治理:RBAC、字段 ACL、row policy 和 mask 统一强制;
  • 成本可控:EXPLAIN 预筛、结果上限、超时和 session/tenant 预算;
  • 默认拒绝:安全能力无法证明时 fail closed;
  • 可审计:配置热重载、异步审计和 OpenTelemetry hook。

运行时安全行为以安全模型为准;Provider 验证边界与证据层级 以兼容矩阵为准;威胁、控制与剩余风险见 威胁模型。所有对外声明的证据汇总见 架构、安全边界与证据索引。不以本页摘要为准。

五分钟体验

只需 Docker 与 Docker Compose:

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

完整的 MCP Inspector 调用、tenant 隔离、mask 和拒绝场景见 五分钟快速体验。

安装与接入

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

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

按角色阅读

首次体验与集成
部署与安全
开发与维护
版本与规划

许可

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
evalcoverage command
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-relation invalidation.
Package cache defines a generic read-result cache with per-relation 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 matching configured entities to it.
Package introspect defines schema introspection: discovering entity metadata from a live database and matching configured entities to it.
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).
relalg/interp
Package interp is the reference interpreter for the committed read-path subset of the relalg IR.
Package interp is the reference interpreter for the committed read-path subset of the relalg IR.
revision
Package revision defines the persisted configuration revision model and the Store boundary.
Package revision defines the persisted configuration revision model and the Store boundary.
revision/revisiontest
Package revisiontest provides the conformance suite every revision.Store implementation must pass, so SQL stores keep the MemoryStore semantics.
Package revisiontest provides the conformance suite every revision.Store implementation must pass, so SQL stores keep the MemoryStore semantics.
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.
eval
runner command
Diagnostic track (-track diagnostic): v5 task set with dimensions, prompt levels, expected behaviors, and counterfactual oracles.
Diagnostic track (-track diagnostic): v5 task set with dimensions, prompt levels, expected behaviors, and counterfactual oracles.
fixtures
v4/generator
Package workload generates the v4 realistic business workload fixture (docs/design/business-workload-model.md): four business modules rendered from one set of table specs into per-dialect DDL/seed SQL, entity configuration, and expected task results.
Package workload generates the v4 realistic business workload fixture (docs/design/business-workload-model.md): four business modules rendered from one set of table specs into per-dialect DDL/seed SQL, entity configuration, and expected task results.
v4/generator/cmd/workloadgen command
Command workloadgen renders the checked-in fixtures/v4 artifacts from the deterministic generator: per-module DDL and seed SQL for every dialect, expected task results (CSV), per-module entity policies, and the runnable combined profile.
Command workloadgen renders the checked-in fixtures/v4 artifacts from the deterministic generator: per-module DDL and seed SQL for every dialect, expected task results (CSV), per-module entity policies, and the runnable combined profile.
internal
benchoverhead command
Command benchoverhead measures the data-plane overhead of the governed tool path against a direct database query on the same connection pool and fixture.
Command benchoverhead measures the data-plane overhead of the governed tool path against a direct database query on the same connection pool and fixture.
conformance
Package conformance is the cross-provider differential conformance suite for the committed read-path IR subset.
Package conformance is the cross-provider differential conformance suite for the committed read-path IR subset.
coveragecheck command
docscheck command
Command docscheck enforces documentation consistency (roadmap v0.1.9 accompanying item): every relative markdown link resolves to an existing file, and the pinned version references (README GA line, roadmap baseline, release notes, CHANGELOG) agree with each other.
Command docscheck enforces documentation consistency (roadmap v0.1.9 accompanying item): every relative markdown link resolves to an existing file, and the pinned version references (README GA line, roadmap baseline, release notes, CHANGELOG) agree with each other.
fmtcheck command
modelscopesmoke command
protocolsmoke command
Command protocolsmoke verifies the two supported MCP transports against a real database: it runs the server binary over stdio and over streamable HTTP, and asserts initialize, tools/list, one allowed read (with masking), and one machine-readable denial on each.
Command protocolsmoke verifies the two supported MCP transports against a real database: it runs the server binary over stdio and over streamable HTTP, and asserts initialize, tools/list, one allowed read (with masking), and one machine-readable denial on each.
quickstartsmoke command
schemagen command
Command schemagen generates core/config/schema.json and the field reference in docs/configuration.md from the configuration structs (their `schema` tags and ApplyDefaults) and the help text in core/config/fields.yaml.
Command schemagen generates core/config/schema.json and the field reference in docs/configuration.md from the configuration structs (their `schema` tags and ApplyDefaults) and the help text in core/config/fields.yaml.
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
admin
Package admin serves the admin API under /admin: sign-in with local accounts, cookie sessions with CSRF tokens, and the GraphQL endpoint.
Package admin serves the admin API under /admin: sign-in with local accounts, cookie sessions with CSRF tokens, and the GraphQL endpoint.
admin/accounts
Package accounts holds the business rules for administrator accounts.
Package accounts holds the business rules for administrator accounts.
admin/auth
Package auth holds what the admin HTTP layer and the GraphQL resolvers share: argon2id password hashing, admin permissions and the signed-in principal on a request context.
Package auth holds what the admin HTTP layer and the GraphQL resolvers share: argon2id password hashing, admin permissions and the signed-in principal on a request context.
admin/graph
Package graph implements the admin GraphQL API.
Package graph implements the admin GraphQL API.
admin/ui
Package ui embeds the built admin console (web/admin).
Package ui embeds the built admin console (web/admin).
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.
configedit
Package configedit applies edits to a stored configuration: it replaces whole sections of a base payload with typed values and runs the result through the same chain as `store import` (strict decoding, defaults, validation, the store secret rule and the deterministic encoding).
Package configedit applies edits to a stored configuration: it replaces whole sections of a base payload with typed values and runs the result through the same chain as `store import` (strict decoding, defaults, validation, the store secret rule and the deterministic encoding).
configstore
Package configstore persists configuration revisions in SQLite or in a PostgreSQL, MySQL or OceanBase database.
Package configstore persists configuration revisions in SQLite or in a PostgreSQL, MySQL or OceanBase database.
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.
providers/sqladapter
Package sqladapter adapts a database/sql pool to the core store interfaces.
Package sqladapter adapts a database/sql pool to the core store interfaces.
revisionops
Package revisionops holds the configuration store operations shared by the `store`/`migrate` CLI and the admin API: normalizing payloads, creating drafts, publishing, rolling back and diffing.
Package revisionops holds the configuration store operations shared by the `store`/`migrate` CLI and the admin API: normalizing payloads, creating drafts, publishing, rolling back and diffing.
telemetry
Package telemetry provides the minimal metrics set for tool calls: a call counter labeled by tool and outcome, a per-tool duration histogram, and an audit-drop counter, served in Prometheus text exposition format.
Package telemetry provides the minimal metrics set for tool calls: a call counter labeled by tool and outcome, a per-tool duration histogram, and an audit-drop counter, served in Prometheus text exposition format.

Jump to

Keyboard shortcuts

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