AI SQL Agent MCP Server

AI SQL Agent MCP Server

Lets AI clients ask natural-language questions about a SQL database with production-safe guardrails, schema grounding, and read-only enforcement.

Category
访问服务器

README

AI SQL Agent MCP Server

Tests License Python FastMCP

A production-hardened Model Context Protocol (MCP) server that lets any MCP-compatible AI client (Claude, LangGraph agents, etc.) ask natural-language questions about a SQL database — safely.

Why this exists

Most public "LLM writes SQL, we run it" examples stop at a single unguarded step: generate SQL, execute it, return rows. That's fine for a demo and dangerous in production — a single hallucinated DROP TABLE or an unbounded query is a real incident, not a hypothetical.

This project treats the SQL-generation step as untrusted input and puts a real safety pipeline around it.

Architecture

MCP Client (Claude / LangGraph / MCP Inspector)
        │
        ▼
 FastMCP Server (this repo)
        │
   ┌────┼─────────────────────────────┐
   ▼    ▼                             ▼
Schema  LLM SQL Generation      Guardrail Layer
Reader  (schema-grounded         (read-only enforcement,
(real   prompt, no guessing)     forbidden-keyword scan,
tables)                          statement-stacking block,
   │                             row-limit injection)
   └──────────────┬──────────────────┘
                  ▼
        Read-only SQLite connection
                  │
                  ▼
      Structured JSON result + trace log

Features

  • Schema-grounded generation — the LLM only ever sees real table/column names pulled live from the database, never guesses.
  • Guardrail layer — blocks any non-SELECT statement, blocks statement-stacking (; DROP TABLE), strips comments before keyword scanning, and caps result size with an injected LIMIT.
  • Defense in depth — the guardrail check runs and the DB connection itself is opened read-only.
  • Optional bearer-token auth on the MCP tool.
  • Structured, correlated logging — every request gets a request ID, logged SQL, latency, and outcome (success / rejected / error).
  • 41 automated tests covering guardrails, schema introspection, generation, and the full integration pipeline — including adversarial cases (SQL hidden in comments, oversized LIMITs, disguised keywords).
  • Health check endpoint (/health) for uptime monitoring.

Why this is different from a typical FastMCP demo

FastMCP (Apache-2.0, PrefectHQ) is used here as the underlying server framework — it handles MCP protocol plumbing so this project can focus entirely on the parts that matter for a real data-access agent: safety, grounding, and observability. Everything in guardrails.py, schema_reader.py, sql_generator.py, and observability.py is original to this project.

Tech stack

Python 3.11+ · FastMCP (Apache-2.0) · Anthropic API · SQLite · pytest · Docker · GitHub Actions

Installation

git clone https://github.com/<your-username>/ai-sql-agent-mcp.git
cd ai-sql-agent-mcp
pip install -e ".[dev]"

Environment variables

Variable Required Description
ANTHROPIC_API_KEY Yes Your Anthropic API key, used for SQL generation
SQL_AGENT_DB_PATH No Path to the SQLite database (default: example.db)
SQL_AGENT_API_TOKEN No If set, ask_database requires this bearer token
SQL_AGENT_MAX_ROWS No Max rows returned per query (default: 500)

Usage

python -m ai_sql_agent_mcp.server

Connect with the MCP Inspector to try it interactively:

npx @modelcontextprotocol/inspector python -m ai_sql_agent_mcp.server

Testing

pytest -v

API

Exposes two MCP tools:

  • ask_database(question: str, api_token: str | None) -> dict — the main tool.
  • describe_schema() -> dict — returns the live database schema.

Deployment

See docs/DEPLOYMENT.md for the free-tier cloud deployment guide (Docker + Fly.io/Render) and live demo instructions.

Security

  • Read-only by construction at two independent layers (guardrail + DB connection mode).
  • No write, DDL, or multi-statement SQL can ever reach the database.
  • API token auth available; recommend enabling it for any public deployment.
  • No secrets are logged; only the generated SQL text and metadata are logged.

Limitations

  • Currently supports SQLite; Postgres/MySQL support would extend SchemaReader.
  • Guardrails are structural (keyword/statement based), not a full SQL parser — sufficient for this threat model but not a substitute for DB-level permissions in a high-stakes production environment.

Roadmap

  • [ ] Postgres/MySQL schema reader
  • [ ] Query result caching
  • [ ] Evaluation harness (NL→SQL accuracy benchmark)
  • [ ] Rate limiting

License

MIT — see LICENSE. Built on FastMCP (Apache-2.0, PrefectHQ).

Author

Built by [your name] as part of an AI/ML engineering portfolio.

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选
mcp-server-qdrant

mcp-server-qdrant

这个仓库展示了如何为向量搜索引擎 Qdrant 创建一个 MCP (Managed Control Plane) 服务器的示例。

官方
精选
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选