MsSqlMCP
MCP Server用于SQL Server数据库架构检查和只读查询执行。
特性
- 只读访问:所有查询都经过验证,以防止数据修改(INSERT、UPDATE、DELETE、DROP、EXEC等被阻止)
- 架构发现:表、列、关系和存储过程
- SQL执行:仅安全SELECT查询
- 双重运输:支持stdio和HTTP/SSE协议
- Windows服务:可以作为Windows服务运行,用于生产部署
- MCP协议:与VS Code Copilot、Claude Desktop和其他MCP客户端兼容
先决条件
- .NET 10(或.NET 9,稍作调整)
- SQL Server
建筑
该项目遵循SOLID原则和依赖注入:
MsSqlMCP/
├── Program.cs # Entry point with DI and dual transport
├── SchemaTool.cs # MCP tool definitions
├── Interfaces/
│ ├── IConnectionFactory.cs # SQL connection abstraction
│ ├── IQueryExecutor.cs # Query execution abstraction
│ ├── ISchemaRepository.cs # Schema queries abstraction
│ └── ISqlQueryValidator.cs # Query validation abstraction
├── Services/
│ ├── SqlConnectionFactory.cs # Connection management
│ ├── SafeQueryExecutor.cs # Validated query execution
│ ├── SchemaRepository.cs # Schema query implementation
│ └── ReadOnlySqlQueryValidator.cs # Security validation (27 blocked keywords)
└── Tests/
└── ReadOnlySqlQueryValidatorTests.cs # 42 security tests配置
连接字符串
编辑 appsettings.json:
{
"ConnectionStrings": {
"DefaultConnection": "Data Source=(local);Initial Catalog=YourDatabase;Encrypt=False;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Urls": "http://localhost:5000"
}跑步
控制台模式(开发)
# Run with both stdio and HTTP transports
dotnet run
# Run with HTTP transport only (for debugging)
dotnet run -- --http-only运行测试
dotnet test --filter "FullyQualifiedName~Tests"MCP客户端配置
选项1:stdio传输(VS代码)
添加到您的VS代码 settings.json:
{
"mcp": {
"servers": {
"MsSqlMCP": {
"type": "stdio",
"command": "dotnet",
"args": ["run", "--project", "c:\\path\\to\\MsSqlMCP.csproj"]
}
}
}
}选项2:HTTP传输(VS代码)
首先,启动服务器:
dotnet run -- --http-only然后添加到您的VS代码中 settings.json:
{
"mcp": {
"servers": {
"MsSqlMCP": {
"type": "http",
"url": "http://localhost:5000/sse",
"autoApprove": [
"get_tables",
"get_columns",
"get_relationships",
"execute_sql",
"get_store_procedure"
]
}
}
}
}选项3:克劳德桌面
添加到 claude_desktop_config.json:
{
"mcpServers": {
"MsSqlMCP": {
"command": "dotnet",
"args": ["run", "--project", "c:\\path\\to\\MsSqlMCP.csproj"]
}
}
}可用工具
| 工具 | 说明 | 必需参数 |
|---|---|---|
GetTables | 获取数据库中的所有表名 | 无 |
GetColumns | 获取特定表的列(字段) | tableName |
GetRelationships | 获取表之间的外键关系 | 无 |
GetStoreProcedure | 获取存储过程定义 | spName |
ExecuteSql | 执行只读SELECT查询 | sqlQuery |
所有工具都接受可选 databaseName 参数,用于查询同一SQL Server实例中的不同数据库。
安全
这 ExecuteSql 该工具只允许SELECT查询。以下语句被阻止:
- 数据操作语言:插入、更新、删除、合并、截断
- 数据定义语言:创建、更改、删除
- 数据控制语言:授予、撤销、拒绝
- 执行:EXEC、EXECUTE、SP_EXECUTESQL、XP\_
- 其他:备份、还原、批量、OPENROWSET、OPENQUERY、OPENDATASOURCE
Windows服务安装
1.发布应用程序
在您的开发机器上:
cd c:\path\to\MsSqlMCP
dotnet publish -c Release -r win-x64 --self-contained true这将在以下位置创建文件: bin\Release\net10.0\win-x64\publish\
2.复制到服务器
复制 publish 文件夹到服务器:
Source: bin\Release\net10.0\win-x64\publish\*
Destination: C:\Services\MsSqlMCP\3.在服务器上配置
编辑 C:\Services\MsSqlMCP\appsettings.json 使用您的SQL Server连接字符串:
{
"ConnectionStrings": {
"DefaultConnection": "Data Source=YOUR_SQL_SERVER;Initial Catalog=YOUR_DATABASE;Encrypt=False;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Urls": "http://localhost:5000"
}4.安装服务
打开 PowerShell作为管理员 并运行:
# Create the Windows Service
sc.exe create MsSqlMCP binPath= "C:\Services\MsSqlMCP\MsSqlMCP.exe --http-only" start= auto DisplayName= "MsSql MCP Server"
# Add description
sc.exe description MsSqlMCP "Model Context Protocol server for SQL Server database inspection"
# Create logs directory
mkdir C:\Services\MsSqlMCP\logs -Force
# Start the service
net start MsSqlMCP
# Verify status
sc.exe query MsSqlMCP5.验证安装
# Check service status
Get-Service -Name MsSqlMCP
# Test the endpoint
Invoke-RestMethod -Uri "http://localhost:5000/sse/tools"服务管理命令
# Stop service
net stop MsSqlMCP
# Start service
net start MsSqlMCP
# Restart service
net stop MsSqlMCP; net start MsSqlMCP
# Uninstall service
net stop MsSqlMCP
sc.exe delete MsSqlMCP防火墙配置(如果远程访问)
# Allow inbound traffic on port 5000
New-NetFirewallRule -DisplayName "MsSqlMCP" -Direction Inbound -Port 5000 -Protocol TCP -Action AllowHTTP API终结点
在HTTP模式下运行时,以下端点可用:
| 端点 | 方法 | 描述 |
|---|---|---|
/sse | MCP协议的GET | SSE流 |
/sse/tools | GET | 列出所有可用工具 |
/sse/invoke | POST | 调用工具 |
示例:通过HTTP调用工具
curl -X POST http://localhost:5000/sse/invoke \
-H "Content-Type: application/json" \
-d '{"Tool": "GetTables", "Params": {}}'Invoke-RestMethod -Uri "http://localhost:5000/sse/invoke" -Method POST -ContentType "application/json" -Body '{"Tool": "GetTables", "Params": {}}'故障排除
服务无法启动
- 检查登录
C:\Services\MsSqlMCP\logs\ - 验证中的连接字符串
appsettings.json - 确保可以从服务帐户访问SQL Server
- 手动运行以查看错误:
C:\Services\MsSqlMCP\MsSqlMCP.exe --http-only
连接问题
- 验证SQL Server是否正在运行
- 检查SQL Server端口的防火墙规则(1433)
- 如果使用Windows身份验证,请确保服务帐户具有数据库访问权限
端口已在使用中
更改端口 appsettings.json:
{
"Urls": "http://localhost:5001"
}许可证
麻省理工学院

