Content
<div align="center">
# ⚡ sqlserver-semantic-mcp
### Not just executing SQL - This is an Enterprise-Level Semantic and Security Brain for AI Agents
Let AI understand your database in 0.5 seconds, automatically find join paths, and be securely guarded by a safety gate.
[](https://pypi.org/project/sqlserver-semantic-mcp/)
[](https://pypi.org/project/sqlserver-semantic-mcp/)
[](https://modelcontextprotocol.io)
[](./LICENSE)
[](#)
**[🚀 Get Started in 3 Minutes](#-get-started-in-3-minutes)** · **[🎯 Why Choose It](#-why-choose-semantic-layer-instead-of-another-sql-executor)** · **[🛠 Killer Features](#-killer-features-and-toolbox)** · **[🛡 Production-Level Security](#-production-level-security)**
📖 Full Documentation: [English](./README.en.md)
</div>
---
> 💡 **In a nutshell:** Connect this MCP server to Claude / Cursor, and your AI will transform from a "clueless intern trying every table" to a "seasoned DBA partner who knows the schema, finds the shortest join path, and never oversteps permissions".
---
## 🎯 Why Choose Semantic Layer Instead of Another SQL Executor?
Throwing a database directly at AI is a recipe for disaster. **Traditional SQL MCP only gives AI a knife; we provide a whole brain.**
| 😱 Traditional SQL MCP Pain Points | ⚡ sqlserver-semantic-mcp Solutions |
|---|---|
| AI **blindly guesses join conditions**, hallucinates non-existent foreign keys, and gets confused results | 🧭 **BFS graph algorithm** explores the real foreign key graph, and `find_join_path` automatically finds the **shortest join path** (up to 5 hops) |
| Every question **bombards system tables** (`sys.*`, `INFORMATION_SCHEMA`), overloading the online database | 🚀 **Dual-layer SQLite caching + schema preheating**: all structural and semantic analysis is locally persisted, with **millisecond-level response and zero pressure on online DB**, and automatically detects schema drift with a lightweight L1 probe |
| AI issues an `UPDATE` without a `WHERE` clause, and **data loss** becomes a reality | 🛡 **JSON Policy Guardrails**: default read-only, mandatory `WHERE` clause, maximum returned/affected rows limit, schema/table whitelist - every SQL query goes through security checks |
| Facing **hundreds of tables**, AI gets lost in token sea and context explosion | 🧠 **Automatic semantic classification**: each table is automatically labeled as Fact / Dimension / Lookup / Bridge / Audit, and columns are automatically identified as audit columns, soft delete columns - **helping AI focus before entering the arena** |
| Schema changes, but AI still uses outdated knowledge from three days ago | 🔄 **Triple Hash version control + Catalog fingerprint probe**: any changes to field types from `nvarchar(4)` to `nvarchar(10)` are caught, and updates are automatically cascaded, **never expiring or wasting re-fetching** |
> 🎯 **Result:** Less token consumption, fewer error retries, faster correct answers - and an AI database tool that's truly ready for production.
---
## 🚀 Get Started in 3 Minutes
No `git clone`, no virtual environment setup, and no installation required. Just [`uv`](https://docs.astral.sh/uv/getting-started/installation/)(one-line installation: `curl -LsSf https://astral.sh/uv/install.sh | sh`), and `uvx` will automatically download, cache, and start the server.
> ⚠️ Replace `localhost` / `YourDatabase` / `sa` / `YourPassword` with your SQL Server connection information.
### 🖥 Claude Desktop (copy and paste to use)
Edit configuration file:
- **macOS:** `~/Library/Application Support/Claude/claude_desktop_config.json`
- **Windows:** `%APPDATA%\Claude\claude_desktop_config.json`
```json
{
"mcpServers": {
"sqlserver-semantic": {
"command": "uvx",
"args": ["sqlserver-semantic-mcp"],
"env": {
"SEMANTIC_MCP_MSSQL_SERVER": "localhost",
"SEMANTIC_MCP_MSSQL_DATABASE": "YourDatabase",
"SEMANTIC_MCP_MSSQL_USER": "sa",
"SEMANTIC_MCP_MSSQL_PASSWORD": "YourPassword"
}
}
}
}
```
Save and restart Claude Desktop - done.✅
### ⌨️ Cursor (copy and paste to use)
Create `.cursor/mcp.json` in the project root directory (or global `~/.cursor/mcp.json`):
```json
{
"mcpServers": {
"sqlserver-semantic": {
"command": "uvx",
"args": ["sqlserver-semantic-mcp"],
"env": {
"SEMANTIC_MCP_MSSQL_SERVER": "localhost",
"SEMANTIC_MCP_MSSQL_DATABASE": "YourDatabase",
"SEMANTIC_MCP_MSSQL_USER": "sa",
"SEMANTIC_MCP_MSSQL_PASSWORD": "YourPassword"
}
}
}
}
```
### 🤖 Claude Code CLI (one-line command)
```bash
claude mcp add sqlserver-semantic -- uvx sqlserver-semantic-mcp \
-e SEMANTIC_MCP_MSSQL_SERVER=localhost \
-e SEMANTIC_MCP_MSSQL_DATABASE=YourDatabase \
-e SEMANTIC_MCP_MSSQL_USER=sa \
-e SEMANTIC_MCP_MSSQL_PASSWORD=YourPassword
```
### 🧪 30-Second Smoke Test (optional)
```bash
SEMANTIC_MCP_MSSQL_SERVER=localhost \
SEMANTIC_MCP_MSSQL_DATABASE=YourDatabase \
SEMANTIC_MCP_MSSQL_USER=sa \
SEMANTIC_MCP_MSSQL_PASSWORD=YourPassword \
uvx sqlserver-semantic-mcp
```
Seeing the cache initialization and tool registration logs means everything is ready. Then say to your AI:
> * "Help me find how to join Orders and Customers, and calculate the average customer order value last month." *
And watch it **get it right on the first try**. 🎉
---
## 🛠 Killer Features and Toolbox
**29 MCP tools**, divided into three core modules - each designed to help AI avoid detours:
### 🧭 1. Exploration and Semantic Module - Let AI Truly "Understand" the Database
| Tool | What it does for you |
|---|---|
| 🔍 `discover_relevant_tables` | Use natural language keywords to directly access relevant tables, eliminating manual schema browsing |
| 🧬 `classify_table` | Automatically determine Fact / Dimension / Lookup / Bridge / Audit, and AI understands the role of each table in seconds |
| 🗺 `find_join_path` | **BFS explores the foreign key graph**, automatically calculating the shortest join chain between two tables - no more guesswork |
| 🤝 `summarize_table_for_joining` | Packages primary keys, join candidate columns, and common filter columns for query writing |
| 🪜 `get_dependency_chain` | Unfolds the entire dependency chain along foreign keys, making impact analysis clear at a glance |
| 📜 `describe_view` / `describe_procedure` | View table and stored procedure definitions, dependencies, and read/write breakdowns (which tables are read, which are written) |
### 🚀 2. Performance and Caching Module - Millisecond-Level Response, Zero Online DB Overhead
| Tool / Mechanism | What it does for you |
|---|---|
| ⚡ **Dual-layer SQLite caching** (built-in) | Structural and semantic caches are locally persisted, with cache-first startup |
| 📡 **L1 Catalog fingerprint probe** (built-in, fully automatic) | Pure catalog queries, millisecond-level detection of schema drift - any changes to field types, lengths, indexes, and view content are captured, **only refreshing tables that have actually changed** |
| 🔄 `refresh_schema_cache` | One-click forced full refresh, with automatic cascading recalculation of semantic analysis |
| 📦 `bundle_context_for_next_step` | Packages the context needed for the next step, **significantly saving tokens** |
| 📊 `get_tool_metrics` | Built-in response size measurement for each tool, making token costs visible |
### 🛡 3. Security and Execution Protection Module - AI Tools That DBAs Can Trust
| Tool | What it does for you |
|---|---|
| 🚦 `plan_or_execute_query` | Intelligent routing: safe queries are executed directly, while dangerous ones are automatically converted into planning and confirmation processes |
| 🕵️ `validate_sql_against_policy` | Verify before execution: operation permissions, mandatory `WHERE` clauses, row limits - if any check fails, it's blocked |
| ⚖️ `estimate_execution_risk` | Quantify the risk level of this SQL query, and take a closer look before proceeding |
| 👀 `preview_safe_query` | No data changes, preview execution plans and samples, and ensure a safe preview |
| ✅ `run_safe_query` | Query execution under policy gate endorsement, with row caps and timeouts fully protected |
---
## 🛡 Production-Level Security Configuration
> **This is the chapter that gets enterprise managers and DBAs on board.** Default behavior is read-only - AI can't even touch an `UPDATE` unless explicitly authorized.
### Environment Variable Protection (effective out of the box)
```bash
SEMANTIC_MCP_MAX_ROWS_RETURNED=1000 # SELECT return row limit
SEMANTIC_MCP_MAX_ROWS_AFFECTED=100 # DML affected row limit (exceeding is rejected)
SEMANTIC_MCP_QUERY_TIMEOUT=30 # Query timeout in seconds
SEMANTIC_MCP_PROBE_INTERVAL_S=60 # Schema drift probe throttling window
```
### JSON Policy Guardrails (advanced hierarchical authorization)
Define AI's permission boundaries with a JSON file, loaded via `SEMANTIC_MCP_POLICY_FILE`:
```json
{
"active_profile": "readonly",
"profiles": {
"readonly": {
"operations": { "select": true },
"constraints": { "max_rows_returned": 1000, "query_timeout_seconds": 30 }
},
"read_write_safe": {
"operations": { "select": true, "insert": true, "update": true },
"constraints": {
"require_where_for_update": true,
"max_rows_affected": 100
}
}
}
}
```
**Three Principles of Security Design:**
- 🔒 **Default read-only** - if the policy file is lost or damaged, it automatically falls back to built-in read-only mode, ensuring no exposure
- 🚧 **Mandatory `WHERE`** - `require_where_for_update` lets "UPDATE without WHERE" be intercepted before execution
- 🎯 **Scope whitelist** - schema/table-level allow and deny lists, with sensitive tables invisible to AI
See the complete policy example in [`config/policy.example.json`](./config/policy.example.json).
---
## 🧩 How It Works
```
AI Agent (Claude / Cursor / Codex)
│ MCP (stdio)
▼
┌─────────────────────────────────────────────┐
│ sqlserver-semantic-mcp │
│ │
│ 🧠 Semantic Layer Classification / Join Path / Dependency Analysis │
│ 🛡 Policy Guardrails Read-only by default / Mandatory WHERE / Row Limits │
│ ⚡ Cache Layer Dual-layer SQLite + L1 Drift Probe │
└─────────────────┬───────────────────────────┘
│ Query only when necessary
▼
🗄 SQL Server (2017+)
```
- **Triple Hash version control** - three sets of fingerprints for structure, objects, and comments, accurately triggering invalidation
- **Table-by-table precise invalidation** - only tables that have actually changed are re-analyzed, while other caches remain intact
- **Background progressive filling** - semantic analysis converges in the background, with startup always in seconds
---
## 📚 Want to Dive Deeper?
| Document | Content |
|---|---|
| 📖 [README.en.md](./README.en.md) | Complete English documentation: architecture, 29 tool overview, environment variables, deployment, and troubleshooting |
| 🛡 [config/policy.example.json](./config/policy.example.json) | Three-level policy template (readonly / read_write_safe / admin) |
---
## ⭐ Like This Project?
If it helped your AI write the correct join on the first try, or gave your DBA a good night's sleep -
**Give it a Star ⭐ in the top right corner, so more people can find it!**
[Report Issues](https://github.com/LukeStackLab/sqlserver-semantic-mcp/issues) · [Contribution Guide](./README.en.md#development) · MIT License © LukeStackLab
Connection Info
You Might Also Like
markitdown
MarkItDown-MCP is a lightweight server for converting URIs to Markdown.
markitdown
Python tool for converting files and office documents to Markdown.
Filesystem
Node.js MCP Server for filesystem operations with dynamic access control.
TrendRadar
TrendRadar: Your hotspot assistant for real news in just 30 seconds.
mempalace
The highest-scoring AI memory system ever benchmarked. And it's free.
mempalace
The highest-scoring AI memory system ever benchmarked. And it's free.