关于 SQL Server MCP Client
SQL Server MCP Client 是基于 .NET 和 MCP C# SDK 构建的 MCP 服务,提供 SQL 查询、存储过程管理和表结构查询等工具。它可以直接在机器上运行,也可以作为 Docker 容器部署。根据连接字符串是否指定数据库,它分为数据库模式和服务器模式两种运行方式。
主要功能
- 01执行 SQL 查询并报告受影响行数
- 02列出表及其结构和行数信息
- 03获取存储过程参数元数据,支持 JSON Schema 格式
- 04后台会话管理长时间运行的查询和存储过程
- 05可配置工具启用状态,写操作默认关闭
- 06查询性能分析,包括 IO 统计和执行计划
适用场景
- 01让 AI 助手查询 SQL Server 数据库结构和数据
- 02在受控环境中通过 MCP 调用存储过程
- 03分析长时间运行查询的执行状态与性能
MCP 相关
该项目是 MCP 服务,向 MCP 客户端暴露 SQL Server 的查询、结构查看和存储过程相关工具。
配置
本地服务的配置在各客户端中通用,复制后粘贴到客户端的 MCP 配置文件即可。
工具
本地服务需要在你的电脑上运行后才能读取工具,维护者暂未提供工具列表。
详细介绍
SQL Server MCP 客户端
0.0.5 中的破坏性变更: 出于安全考虑,查询和存储过程执行工具现在默认处于禁用状态。如果你依赖之前的默认设置,现在必须将相应的环境变量明确设置为
"true",才能启用这些工具:
DatabaseConfiguration__EnableExecuteQueryDatabaseConfiguration__EnableExecuteStoredProcedureDatabaseConfiguration__EnableStartQueryDatabaseConfiguration__EnableStartStoredProcedure
一款功能全面的 Microsoft SQL Server 客户端,采用模型上下文协议(MCP)实现。该服务通过简洁的 MCP 接口提供丰富的 SQL Server 功能,包括查询执行、架构发现和存储过程管理。
概览
SQL Server MCP 客户端基于 .NET Core 和模型上下文协议 C# SDK(github.com/modelcontextprotocol/csharp-sdk)构建。它提供用于执行 SQL 查询、管理存储过程、列出表,以及从 SQL Server 数据库检索完整架构信息的工具。该服务轻量而强大,展示了如何构建具备实用数据库功能的稳健 MCP 服务。它既可以直接部署在计算机上,也可以作为 Docker 容器部署。
MCP 客户端以以下两种模式之一运行:
- 数据库模式:如果连接字符串中指定了特定数据库,则只能执行该数据库范围内的操作
- 服务器模式:如果连接字符串中未指定数据库,则可以执行所有数据库范围内的服务器级操作
功能
核心数据库操作
- 在已连接的 SQL Server 数据库上执行 SQL 查询
- 列出所有表,并提供架构和行数信息
- 检索特定表的详细架构信息
- 全面的存储过程管理与执行功能
存储过程支持
- 参数发现:以表格或 JSON Schema 格式获取详细的参数信息
- 类型安全的执行:根据参数元数据自动进行 JSON 到 SQL 类型的转换
- 丰富的元数据:支持输入/输出参数、默认值和数据类型约束
- 跨数据库操作:跨不同数据库执行存储过程(服务器模式)
高级功能
- JSON Schema 输出:参数元数据与验证工具兼容
- 不区分大小写的参数:通过 @ 前缀规范化,灵活处理参数名称
- SQL Server 功能检测:全面报告功能支持情况
- 双模式架构:针对单数据库和多数据库场景进行优化
- 可配置超时:支持默认超时和按操作配置超时,并提供运行时管理工具
- 后台会话管理:通过基于会话的监控执行长时间运行的查询和存储过程
- 执行计时:自动报告查询和存储过程结果的挂钟时间及 SQL Server 报告的耗时
- 查询分析:可选的按表 IO 统计信息和实际 XML 执行计划,用于性能分析
- 受影响的行数:自动报告 DML 操作所影响的行数
安全与配置
- 可配置工具的启用状态,保障安全
- 基于环境的配置
- 提供标准化错误消息的全面错误处理
- 根据 SQL Server 元数据验证输入
开始使用
先决条件
- .NET 10.0 SDK(用于本地开发/部署)
- Docker(用于容器部署)
构建说明(用于开发)
如果要从源代码构建项目:
-
克隆此仓库:
git clone https://github.com/aadversteeg/mssqlclient-mcp-server.git -
导航至源代码目录:
cd mssqlclient-mcp-server/src -
构建项目:
dotnet build -
运行单元测试:
dotnet test
运行集成测试
集成测试会使用真实的 SQL Server 实例验证 MCP 服务。测试框架会自动管理 Docker 容器:查找空闲端口(范围为 14330–14339),启动名称唯一的 SQL Server 容器,运行所有测试,并在完成后移除容器。
唯一的前提条件是 Docker 正在运行:
cd tst
dotnet test --filter "TestType=Integration"
集成测试涵盖数据库模式(连接字符串包含 Database=)和服务器模式(连接字符串不包含 Database=),包括工具元数据验证,以及查询执行、表列表和架构检索的功能测试。
集成测试也会通过 Integration Tests 工作流在 CI 中自动运行,该工作流可从 GitHub Actions 选项卡手动触发。
Docker 支持
Docker Hub
SQL Server MCP Client 可在 Docker Hub 上获取。
# Pull the latest version
docker pull aadversteeg/mssqlclient-mcp-server:latest
手动构建 Docker 镜像
如果需要自行构建 Docker 镜像:
# Navigate to the repository root
cd mssqlclient-mcp-server
# Build the Docker image
docker build -f src/Core.Infrastructure.McpServer/Dockerfile -t mssqlclient-mcp-server:latest src/
# Run the locally built image
docker run -d --name mssql-mcp -e "MSSQL_CONNECTIONSTRING=Server=your_server;Database=your_db;User Id=your_user;Password=your_password;TrustServerCertificate=True;" mssqlclient-mcp-server:latest
推送到本地注册表
要推送到本地注册表:
# Build the Docker image
docker build -f src/Core.Infrastructure.McpServer/Dockerfile -t localhost:5000/mssqlclient-mcp-server:latest src/
# Push to local registry
docker push localhost:5000/mssqlclient-mcp-server:latest
使用本地注册表
如果你已将镜像推送到运行在端口 5000 上的本地注册表,可以从中拉取:
# Pull from local registry
docker pull localhost:5000/mssqlclient-mcp-server:latest
.NET 工具
SQL Server MCP Client 可作为 NuGet 上的 .NET 全局工具使用。
安装
dotnet tool install --global Ave.McpServer.MsSqlClient
运行
ave-mcpserver-mssqlclient
一次性执行(无需永久安装)
使用 .NET 10 SDK,你可以通过 dotnet tool exec 运行工具,而无需全局安装:
dotnet tool exec -y ave.mcpserver.mssqlclient
-y 标志会自动接受提示。工具会缓存在本地,但不会添加到 PATH。
配置 Claude Desktop / Claude Code
将服务配置添加到配置文件中的 mcpServers 部分。
默认情况下,仅启用只读工具(列出表、查看架构、列出存储过程)。要启用查询和存储过程执行功能,请添加相应的环境变量并将其设为 "true":
| 设置 | 描述 | 默认值 |
|---|---|---|
DatabaseConfiguration__EnableExecuteQuery | 启用 execute_query / execute_query_in_database 工具 | false |
DatabaseConfiguration__EnableExecuteStoredProcedure | 启用 execute_stored_procedure / execute_stored_procedure_in_database 工具 | false |
DatabaseConfiguration__EnableStartQuery | 启用 start_query / start_query_in_database 会话工具 | false |
DatabaseConfiguration__EnableStartStoredProcedure | 启用 start_stored_procedure / start_stored_procedure_in_database 会话工具 | false |
DatabaseConfiguration__MaxCellOutputLength | 查询结果中每个单元格显示的最大字符数。超过此长度的值会被截断并以 ... 结尾。设为 0 可禁用截断。 | 40 |
使用 .NET 工具
需要 .NET 10 SDK。此方法会在首次使用时自动下载工具,并在后续运行时更新到最新版本。
"mssql": {
"command": "dotnet",
"args": [
"tool",
"exec",
"-y",
"ave.mcpserver.mssqlclient"
],
"env": {
"MSSQL_CONNECTIONSTRING": "Data Source=localhost;Integrated Security=True;MultipleActiveResultSets=True;TrustServerCertificate=True;",
"DatabaseConfiguration__EnableExecuteQuery": "true",
"DatabaseConfiguration__EnableExecuteStoredProcedure": "true",
"DatabaseConfiguration__EnableStartQuery": "true",
"DatabaseConfiguration__EnableStartStoredProcedure": "true"
}
}
使用全局安装
需要 .NET 10 SDK。安装一次工具后,即可直接使用。
dotnet tool install --global Ave.McpServer.MsSqlClient
"mssql": {
"command": "ave-mcpserver-mssqlclient",
"env": {
"MSSQL_CONNECTIONSTRING": "Data Source=localhost;Integrated Security=True;MultipleActiveResultSets=True;TrustServerCertificate=True;",
"DatabaseConfiguration__EnableExecuteQuery": "true",
"DatabaseConfiguration__EnableExecuteStoredProcedure": "true",
"DatabaseConfiguration__EnableStartQuery": "true",
"DatabaseConfiguration__EnableStartStoredProcedure": "true"
}
}
更新方式:dotnet tool update --global Ave.McpServer.MsSqlClient
MCP 协议用法
客户端集成
要从应用程序连接到 SQL Server MCP Client:
- 使用 Model Context Protocol C# SDK 或任何兼容 MCP 的客户端
- 配置客户端以连接到服务端点
- 调用下文所述的可用工具
可用工具
根据服务运行的模式不同,可用工具也会有所不同,其中部分工具在两种模式下均可使用:
通用工具(两种模式下均可用)
server_capabilities
返回有关已连接 SQL Server 实例的功能和特性的详细信息。
请求示例:
{
"name": "server_capabilities",
"parameters": {}
}
服务器模式下的响应示例:
{
"version": "Microsoft SQL Server 2019",
"majorVersion": 15,
"minorVersion": 0,
"buildNumber": 4123,
"edition": "Enterprise Edition",
"isAzureSqlDatabase": false,
"isAzureVmSqlServer": false,
"isOnPremisesSqlServer": true,
"toolMode": "server",
"features": {
"supportsPartitioning": true,
"supportsColumnstoreIndex": true,
"supportsJson": true,
"supportsInMemoryOLTP": true,
"supportsRowLevelSecurity": true,
"supportsDynamicDataMasking": true,
"supportsDataCompression": true,
"supportsDatabaseSnapshots": true,
"supportsQueryStore": true,
"supportsResumableIndexOperations": true,
"supportsGraphDatabase": true,
"supportsAlwaysEncrypted": true,
"supportsExactRowCount": true,
"supportsDetailedIndexMetadata": true,
"supportsTemporalTables": true
}
}
此工具适用于:
- 确定 SQL Server 实例中可用的功能
- 调试兼容性问题
- 了解将使用哪些查询模式
- 验证当前处于服务器模式还是数据库模式
get_command_timeout
返回当前超时配置设置。
请求示例:
{
"name": "get_command_timeout",
"parameters": {}
}
响应示例:
{
"defaultCommandTimeoutSeconds": 30,
"connectionTimeoutSeconds": 15,
"maxConcurrentSessions": 10,
"sessionCleanupIntervalMinutes": 60,
"totalToolCallTimeoutSeconds": 120,
"timestamp": "2024-12-19 10:30:45 UTC"
}
set_command_timeout
更新所有新操作的默认命令超时时间。
注意: 配置了 TotalToolCallTimeoutSeconds 时,实际超时时间将取此值与剩余总超时时间中的较小值。这样可确保操作在工具调用总超时限制内完成。
参数:
timeoutSeconds(必需):新的超时时间,单位为秒(1-3600)
请求示例:
{
"name": "set_command_timeout",
"parameters": {
"timeoutSeconds": 120
}
}
响应示例:
{
"message": "Default command timeout updated successfully",
"oldTimeoutSeconds": 30,
"newTimeoutSeconds": 120,
"note": "This change only affects new operations. Existing sessions will continue with their original timeout settings.",
"timestamp": "2024-12-19 10:31:00 UTC"
}
会话管理工具
这些工具可通过后台会话管理长时间运行的查询和存储过程。当操作可能超过 TotalToolCallTimeoutSeconds 限制,或需要并发运行多个操作时,这些工具尤其有用。
get_session_status
检查正在运行的查询或存储过程会话的状态。
参数:
sessionId(必需):要检查的会话 ID
请求示例:
{
"name": "get_session_status",
"parameters": {
"sessionId": 12345
}
}
响应示例:
{
"sessionId": 12345,
"type": "query",
"query": "SELECT * FROM LargeTable",
"databaseName": "Northwind",
"startTime": "2024-12-19 10:30:00 UTC",
"endTime": "2024-12-19 10:35:23 UTC",
"duration": "323.5 seconds",
"status": "completed",
"isRunning": false,
"rowCount": 1500000,
"error": null,
"timeoutSeconds": 600,
"serverElapsedTimeMs": 323000,
"serverCpuTimeMs": 18500,
"rowsAffected": null,
"ioStats": [
{ "table": "LargeTable", "logicalReads": 45230, "physicalReads": 120, "readAheadReads": 44800 }
],
"executionPlanXml": null
}
以下字段在可用时会包含在内,否则为 null:
serverElapsedTimeMs/serverCpuTimeMs:SQL Server 端的计时信息(始终采集)rowsAffected:DML 操作影响的总行数(始终采集)ioStats:每个表的 IO 统计信息(仅当启动工具中的includeIoStats为true时提供)executionPlanXml:实际的 XML 执行计划(仅当启动工具中的includeExecutionPlan为true时提供)
get_session_results
获取已完成或正在运行的查询/存储过程会话的结果。
参数:
sessionId(必需):要获取结果的会话 IDmaxRows(可选):返回的最大行数
请求示例:
{
"name": "get_session_results",
"parameters": {
"sessionId": 12345,
"maxRows": 100
}
}
响应示例:
{
"sessionId": 12345,
"type": "query",
"status": "completed",
"rowCount": 1500000,
"results": "| CustomerID | CompanyName | ContactName |\n| ---------- | ----------- | ----------- |\n| ALFKI | Alfreds Futterkiste | Maria Anders |\n...\n... (showing first 100 rows of 1500000 total)",
"maxRowsApplied": 100,
"serverElapsedTimeMs": 323000,
"serverCpuTimeMs": 18500,
"rowsAffected": null,
"ioStats": [
{ "table": "Customers", "logicalReads": 42, "physicalReads": 0, "readAheadReads": 0 }
],
"executionPlanXml": null
}
stop_session
停止正在运行的查询或存储过程会话。
参数:
sessionId(必需):要停止的会话 ID
请求示例:
{
"name": "stop_session",
"parameters": {
"sessionId": 12345
}
}
响应示例:
{
"sessionId": 12345,
"status": "cancelled",
"message": "Session cancelled successfully",
"timestamp": "2024-12-19 10:32:15 UTC"
}
list_sessions
列出所有查询和存储过程会话。
参数:
status(可选):按状态筛选——"all"(默认值)、"running" 或 "completed"
请求示例:
{
"name": "list_sessions",
"parameters": {
"status": "running"
}
}
响应示例:
{
"filter": "running",
"totalSessions": 2,
"sessions": [
{
"sessionId": 12345,
"type": "query",
"query": "SELECT * FROM LargeTable...",
"databaseName": "Northwind",
"startTime": "2024-12-19 10:30:00 UTC",
"duration": "45.2 seconds",
"status": "running",
"isRunning": true,
"rowCount": 0,
"hasError": false
},
{
"sessionId": 12346,
"type": "storedprocedure",
"query": "GenerateMonthlyReport",
"databaseName": "Sales",
"startTime": "2024-12-19 10:25:00 UTC",
"duration": "320.1 seconds",
"status": "running",
"isRunning": true,
"rowCount": 0,
"hasError": false
}
],
"timestamp": "2024-12-19 10:30:45 UTC"
}
数据库模式工具
使用连接字符串连接到特定数据库时,可使用以下工具:
execute_query
在已连接的 SQL Server 数据库上执行 SQL 查询。
参数:
query(必需):要执行的 SQL 查询。timeoutSeconds(可选):命令超时时间,单位为秒。覆盖默认超时时间。includeIoStats(可选):包含每个表的 IO 统计信息。默认为false。includeExecutionPlan(可选):包含实际的 XML 执行计划。默认为false。maxCellOutputLength(可选):每个单元格显示的最大字符数。超过此长度的值将以...截断。设为0可禁用截断。若未指定,则使用服务器默认值(MaxCellOutputLength,默认为40)。
请求示例:
{
"name": "execute_query",
"parameters": {
"query": "SELECT TOP 5 * FROM Customers",
"includeIoStats": true
}
}
响应示例:
| CustomerID | CompanyName | ContactName |
| ---------- | -------------------------------- | ------------------ |
| ALFKI | Alfreds Futterkiste | Maria Anders |
| ANATR | Ana Trujillo Emparedados y h... | Ana Trujillo |
| ANTON | Antonio Moreno Taquería | Antonio Moreno |
| AROUT | Around the Horn | Thomas Hardy |
| BERGS | Berglunds snabbköp | Christina Berglund |
Total rows: 5
Execution time: 42ms (server: 38ms, CPU: 12ms)
IO stats: Customers (logical: 12, physical: 0, read-ahead: 0)
执行计时
计时行显示:
- 总执行时间:客户端测量的实际耗时(包括网络延迟和读取结果的时间)
- 服务器耗时:SQL Server 报告的查询执行时间
- CPU 时间:SQL Server 消耗的 CPU 时间
如果 SQL Server 计时信息不可用,则只显示客户端计时:Execution time: 42ms
所有执行工具的输出中始终包含执行计时信息。
IO 统计信息
当 includeIoStats 设为 true 时,输出中会附加每个表的 IO 统计信息:
IO stats: Customers (logical: 12, physical: 0, read-ahead: 0), Orders (logical: 42, physical: 3, read-ahead: 40)
此信息会显示每个被访问表的:
- 逻辑读取:从缓冲区缓存读取的页
- 物理读取:从磁盘读取的页
- 预读:为该查询加载到缓存中的页
IO 统计信息有助于识别缺失的索引和低效的查询计划。
执行计划
当 includeExecutionPlan 设为 true 时,实际 XML 执行计划会包含在输出末尾:
Execution plan:
<ShowPlanXML xmlns="http://schemas.microsoft.com/sqlserver/2004/07/showplan" ...>...</ShowPlanXML>
XML 执行计划可以保存为 .sqlplan 文件,并在 SQL Server Management Studio 或 Azure Data Studio 中打开进行可视化分析。
受影响的行数
对于不返回结果行的 DML 操作(INSERT、UPDATE、DELETE),输出中会包含:
Query executed successfully. No results returned.
Rows affected: 5
Execution time: 12ms (server: 8ms, CPU: 2ms)
受影响行数的报告始终启用,且不会产生额外开销。
这些分析功能(includeIoStats、includeExecutionPlan)也适用于 execute_query_in_database、execute_stored_procedure、execute_stored_procedure_in_database 和所有会话启动工具。
list_tables
列出已连接的 SQL Server 数据库中的所有表,并显示架构和行数信息。
请求示例:
{
"name": "list_tables",
"parameters": {}
}
响应示例:
Available Tables:
Schema | Table Name | Row Count
------ | ---------- | ---------
dbo | Customers | 91
dbo | Products | 77
dbo | Orders | 830
dbo | Employees | 9
get_table_schema
获取已连接的 SQL Server 数据库中某个表的架构。
参数:
tableName(必需):要获取架构信息的表名。
请求示例:
{
"name": "get_table_schema",
"parameters": {
"tableName": "Customers"
}
}
响应示例:
Schema for table: Customers
Column Name | Data Type | Max Length | Is Nullable
----------- | --------- | ---------- | -----------
CustomerID | nchar | 5 | NO
CompanyName | nvarchar | 40 | NO
ContactName | nvarchar | 30 | YES
ContactTitle| nvarchar | 30 | YES
Address | nvarchar | 60 | YES
City | nvarchar | 15 | YES
Region | nvarchar | 15 | YES
PostalCode | nvarchar | 10 | YES
Country | nvarchar | 15 | YES
Phone | nvarchar | 24 | YES
Fax | nvarchar | 24 | YES
list_stored_procedures
列出当前数据库中的所有存储过程及其详细信息。
请求示例:
{
"name": "list_stored_procedures",
"parameters": {}
}
响应示例:
Available Stored Procedures in 'Northwind':
Schema | Procedure Name | Parameters | Last Execution | Execution Count | Created Date
-------- | ------------------------------- | ---------- | ----------------- | --------------- | -------------------
dbo | GetCustomerOrders | 2 | 2024-01-15 10:30:00 | 145 | 2023-12-01 09:00:00
dbo | UpdateProductPrice | 3 | 2024-01-14 16:45:00 | 89 | 2023-11-15 14:30:00
dbo | CreateNewCustomer | 5 | N/A | N/A | 2024-01-10 11:20:00
get_stored_procedure_definition
获取存储过程的 SQL 定义。
参数:
procedureName(必需):存储过程名称。
请求示例:
{
"name": "get_stored_procedure_definition",
"parameters": {
"procedureName": "GetCustomerOrders"
}
}
get_stored_procedure_parameters
以表格或 JSON Schema 格式获取存储过程的参数信息。
参数:
procedureName(必需):存储过程名称。format(可选):输出格式——"table"(默认)或 "json"。
请求示例(表格格式):
{
"name": "get_stored_procedure_parameters",
"parameters": {
"procedureName": "CreateNewCustomer",
"format": "table"
}
}
响应示例(表格格式):
Parameters for stored procedure: CreateNewCustomer
| Parameter | Type | Required | Direction | Default |
|-----------|------|----------|-----------|---------|
| CompanyName | nvarchar(40) | Yes | INPUT | - |
| ContactName | nvarchar(30) | No | INPUT | NULL |
| City | nvarchar(15) | No | INPUT | NULL |
| Country | nvarchar(15) | No | INPUT | USA |
Example usage:
```json
{
"CompanyName": "Acme Corp",
"ContactName": "John Doe",
"City": "Seattle",
"Country": "USA"
}
Example request (JSON Schema format):
```json
{
"name": "get_stored_procedure_parameters",
"parameters": {
"procedureName": "CreateNewCustomer",
"format": "json"
}
}
响应示例(JSON Schema 格式):
{
"procedureName": "CreateNewCustomer",
"description": "Parameter schema for stored procedure CreateNewCustomer",
"parameters": {
"type": "object",
"properties": {
"CompanyName": {
"type": "string",
"maxLength": 40,
"sqlType": "nvarchar(40)",
"sqlParameter": "@CompanyName",
"position": 1,
"isOutput": false,
"description": "Parameter @CompanyName of type nvarchar(40)"
},
"ContactName": {
"type": "string",
"maxLength": 30,
"sqlType": "nvarchar(30)",
"sqlParameter": "@ContactName",
"position": 2,
"isOutput": false,
"hasDefault": true,
"defaultValue": null,
"description": "Parameter @ContactName of type nvarchar(30)"
},
"Country": {
"type": "string",
"maxLength": 15,
"sqlType": "nvarchar(15)",
"sqlParameter": "@Country",
"position": 4,
"isOutput": false,
"hasDefault": true,
"defaultValue": "USA",
"description": "Parameter @Country of type nvarchar(15)"
}
},
"required": ["CompanyName"],
"additionalProperties": false
},
"returnValue": {
"type": "integer",
"sqlType": "int",
"description": "Return code (0 for success)"
}
}
execute_stored_procedure
执行存储过程,并自动转换参数类型。
参数:
procedureName(必需):存储过程名称。parameters(必需):包含参数值的 JSON 字符串。timeoutSeconds(可选):命令超时时间,单位为秒。此值会覆盖默认超时时间。includeIoStats(可选):包含每个表的 IO 统计信息。默认值为false。includeExecutionPlan(可选):包含实际 XML 执行计划。默认值为false。maxCellOutputLength(可选):每个单元格显示的最大字符数。超过此长度的内容会截断并以...结尾。设为0可禁用截断。若未指定,则使用服务端默认值(MaxCellOutputLength,默认值为40)。
请求示例:
{
"name": "execute_stored_procedure",
"parameters": {
"procedureName": "CreateNewCustomer",
"parameters": "{\"CompanyName\": \"Acme Corp\", \"ContactName\": \"John Doe\", \"City\": \"Seattle\"}"
}
}
功能:
- 根据存储过程元数据自动将 JSON 类型转换为 SQL 类型
- 支持
@ParameterName和ParameterName两种格式 - 参数匹配不区分大小写
- 提供包含参数验证的详尽错误消息
- 支持输出参数和返回值
start_query
在已连接的数据库中后台启动 SQL 查询,并返回会话 ID 以便检查进度。适用于长时间运行的查询。
参数:
query(必需):要执行的 SQL 查询timeoutSeconds(可选):超时时间,单位为秒。若未指定,则使用默认超时时间includeIoStats(可选):包含每个表的 IO 统计信息。默认值为false。includeExecutionPlan(可选):包含实际 XML 执行计划。默认值为false。
请求示例:
{
"name": "start_query",
"parameters": {
"query": "SELECT * FROM LargeTable WHERE ProcessingDate >= '2024-01-01'",
"timeoutSeconds": 600
}
}
响应示例:
{
"sessionId": 12345,
"startTime": "2024-12-19 10:30:00 UTC",
"query": "SELECT * FROM LargeTable WHERE ProcessingDate >= '2024-01-01'",
"databaseName": "connected database",
"timeoutSeconds": 600,
"status": "running",
"message": "Query started successfully. Use get_session_status to check progress."
}
start_stored_procedure
在后台启动存储过程执行。返回会话 ID,以便检查进度。最适合运行时间较长的存储过程。
参数:
procedureName(必需):要执行的存储过程名称parameters(可选):包含存储过程参数的 JSON 对象(默认值:"{}")timeoutSeconds(可选):超时时间(秒)。若未指定,则使用默认超时时间includeIoStats(可选):包含每个表的 IO 统计信息。默认值为false。includeExecutionPlan(可选):包含实际的 XML 执行计划。默认值为false。
请求示例:
{
"name": "start_stored_procedure",
"parameters": {
"procedureName": "GenerateMonthlyReport",
"parameters": "{\"Month\": 12, \"Year\": 2024, \"IncludeDetails\": true}",
"timeoutSeconds": 1200
}
}
响应示例:
{
"sessionId": 12346,
"startTime": "2024-12-19 10:35:00 UTC",
"procedureName": "GenerateMonthlyReport",
"databaseName": "connected database",
"parameters": {"Month": 12, "Year": 2024, "IncludeDetails": true},
"timeoutSeconds": 1200,
"status": "running",
"message": "Stored procedure started successfully. Use get_session_status to check progress."
}
服务端模式工具
如果连接字符串中未指定特定数据库,连接后即可使用以下附加工具:
list_databases
列出 SQL Server 实例上的所有数据库。
请求示例:
{
"name": "list_databases",
"parameters": {}
}
响应示例:
Available Databases:
Name | State | Size (MB) | Owner | Compatibility
---------- | ------ | --------- | --------- | -------------
master | ONLINE | 10.25 | sa | 160
tempdb | ONLINE | 25.50 | sa | 160
model | ONLINE | 8.00 | sa | 160
msdb | ONLINE | 15.75 | sa | 160
Northwind | ONLINE | 45.25 | sa | 160
execute_query_in_database
在指定数据库中执行 SQL 查询。
参数:
databaseName(必需):要执行查询的数据库名称。query(必需):要执行的 SQL 查询。timeoutSeconds(可选):命令超时时间(秒)。覆盖默认超时时间。includeIoStats(可选):包含每个表的 IO 统计信息。默认值为false。includeExecutionPlan(可选):包含实际的 XML 执行计划。默认值为false。maxCellOutputLength(可选):每个单元格显示的最大字符数。超过此长度的内容会被截断,并以...结尾。设为0可禁用截断。若未指定,则使用服务端默认值(MaxCellOutputLength,默认值为40)。
请求示例:
{
"name": "execute_query_in_database",
"parameters": {
"databaseName": "Northwind",
"query": "SELECT TOP 5 * FROM Customers"
}
}
list_tables_in_database
列出指定数据库中的所有表。
参数:
databaseName(必需):要列出其表的数据库名称。
请求示例:
{
"name": "list_tables_in_database",
"parameters": {
"databaseName": "Northwind"
}
}
get_table_schema_in_database
获取指定数据库中某个表的架构。
参数:
databaseName(必需):包含该表的数据库名称。tableName(必需):要获取架构信息的表名称。
请求示例:
{
"name": "get_table_schema_in_database",
"parameters": {
"databaseName": "Northwind",
"tableName": "Customers"
}
}
list_stored_procedures_in_database
列出指定数据库中的所有存储过程。
参数:
databaseName(必需):要列出其存储过程的数据库名称。
请求示例:
{
"name": "list_stored_procedures_in_database",
"parameters": {
"databaseName": "Northwind"
}
}
get_stored_procedure_definition_in_database
获取指定数据库中某个存储过程的 SQL 定义。
参数:
databaseName(必需):包含该存储过程的数据库名称。procedureName(必需):存储过程名称。
请求示例:
{
"name": "get_stored_procedure_definition_in_database",
"parameters": {
"databaseName": "Northwind",
"procedureName": "GetCustomerOrders"
}
}
get_stored_procedure_parameters (Server Mode)
获取任意数据库中某个存储过程的参数信息。
参数:
procedureName(必需):存储过程名称。databaseName(可选):包含该存储过程的数据库名称。format(可选):输出格式——"table"(默认值)或"json"。
请求示例:
{
"name": "get_stored_procedure_parameters",
"parameters": {
"procedureName": "CreateNewCustomer",
"databaseName": "Northwind",
"format": "json"
}
}
execute_stored_procedure_in_database
在指定数据库中执行存储过程,并自动转换参数类型。
参数:
databaseName(必填):包含该存储过程的数据库名称。procedureName(必填):存储过程名称。parameters(必填):包含参数值的 JSON 字符串。timeoutSeconds(可选):命令超时时间(秒)。会覆盖默认超时时间。includeIoStats(可选):包含每个表的 IO 统计信息。默认为false。includeExecutionPlan(可选):包含实际的 XML 执行计划。默认为false。maxCellOutputLength(可选):每个单元格显示的最大字符数。超过此长度的内容会截断并以...表示。设为0可禁用截断。若未指定,则使用服务端默认值(MaxCellOutputLength,默认为40)。
请求示例:
{
"name": "execute_stored_procedure_in_database",
"parameters": {
"databaseName": "Northwind",
"procedureName": "CreateNewCustomer",
"parameters": "{\"CompanyName\": \"Acme Corp\", \"ContactName\": \"John Doe\"}"
}
}
start_query_in_database
在指定数据库中于后台启动 SQL 查询。返回用于检查进度的会话 ID。适用于长时间运行的查询(服务端模式)。
参数:
databaseName(必填):执行查询的数据库名称query(必填):要执行的 SQL 查询timeoutSeconds(可选):可选的超时时间(秒)。若未指定,则使用默认超时时间includeIoStats(可选):包含每个表的 IO 统计信息。默认为false。includeExecutionPlan(可选):包含实际的 XML 执行计划。默认为false。
请求示例:
{
"name": "start_query_in_database",
"parameters": {
"databaseName": "DataWarehouse",
"query": "EXEC sp_refreshview 'vw_SalesSummary'; SELECT * FROM vw_SalesSummary",
"timeoutSeconds": 900
}
}
响应示例:
{
"sessionId": 12347,
"startTime": "2024-12-19 10:40:00 UTC",
"query": "EXEC sp_refreshview 'vw_SalesSummary'; SELECT * FROM vw_SalesSummary",
"databaseName": "DataWarehouse",
"timeoutSeconds": 900,
"status": "running",
"message": "Query started successfully. Use get_session_status to check progress."
}
start_stored_procedure_in_database
在指定数据库中于后台启动存储过程。返回用于检查进度的会话 ID。适用于长时间运行的存储过程(服务端模式)。
参数:
databaseName(必填):包含该存储过程的数据库名称procedureName(必填):要执行的存储过程名称parameters(可选):包含存储过程参数的 JSON 对象(默认值:{})timeoutSeconds(可选):可选的超时时间(秒)。若未指定,则使用默认超时时间includeIoStats(可选):包含每个表的 IO 统计信息。默认为false。includeExecutionPlan(可选):包含实际的 XML 执行计划。默认为false。
请求示例:
{
"name": "start_stored_procedure_in_database",
"parameters": {
"databaseName": "Analytics",
"procedureName": "sp_BuildDataMart",
"parameters": "{\"StartDate\": \"2024-01-01\", \"EndDate\": \"2024-12-31\", \"RebuildIndexes\": true}",
"timeoutSeconds": 3600
}
}
响应示例:
{
"sessionId": 12348,
"startTime": "2024-12-19 10:45:00 UTC",
"procedureName": "sp_BuildDataMart",
"databaseName": "Analytics",
"parameters": {"StartDate": "2024-01-01", "EndDate": "2024-12-31", "RebuildIndexes": true},
"timeoutSeconds": 3600,
"status": "running",
"message": "Stored procedure started successfully. Use get_session_status to check progress."
}
配置
工具安全配置
服务端提供了细粒度控制,可管理哪些潜在危险操作可用:
查询执行安全性
出于安全原因,SQL 查询执行工具默认处于禁用状态。要启用这些工具,请将 EnableExecuteQuery 配置项设为 true。
存储过程执行安全性
出于安全原因,存储过程执行工具默认处于禁用状态。要启用这些工具,请将 EnableExecuteStoredProcedure 配置项设为 true。
基于会话的执行安全性
出于安全原因,基于会话的查询执行工具默认处于禁用状态。要启用这些工具,请将 EnableStartQuery 配置项设为 true。
出于安全原因,基于会话的存储过程执行工具默认处于禁用状态。要启用这些工具,请将 EnableStartStoredProcedure 配置项设为 true。
可通过以下几种方式进行配置:
- 在
appsettings.json文件中:
{
"DatabaseConfiguration": {
"EnableExecuteQuery": true,
"EnableExecuteStoredProcedure": true,
"EnableStartQuery": true,
"EnableStartStoredProcedure": true
}
}
- 运行容器时,将其设为环境变量:
docker run \
-e "DatabaseConfiguration__EnableExecuteQuery=true" \
-e "DatabaseConfiguration__EnableExecuteStoredProcedure=true" \
-e "DatabaseConfiguration__EnableStartQuery=true" \
-e "DatabaseConfiguration__EnableStartStoredProcedure=true" \
-e "MSSQL_CONNECTIONSTRING=Server=your_server;..." \
aadversteeg/mssqlclient-mcp-server:latest
- 在 Claude Desktop 配置中:
"mssql": {
"command": "dotnet",
"args": [
"YOUR_PATH_TO_DLL\\Core.Infrastructure.McpServer.dll"
],
"env": {
"MSSQL_CONNECTIONSTRING": "Server=your_server;...",
"DatabaseConfiguration__EnableExecuteQuery": "true",
"DatabaseConfiguration__EnableExecuteStoredProcedure": "true",
"DatabaseConfiguration__EnableStartQuery": "true",
"DatabaseConfiguration__EnableStartStoredProcedure": "true"
}
}
当这些设置为 false(默认值)时,相应的执行工具不会注册,也不会提供给客户端使用。当你只希望允许只读操作时,这可以提供额外的安全保障。
超时配置
SQL Server MCP Client 提供多级全面的超时配置,以满足各种工作负载需求。
默认超时设置
在 appsettings.json 中配置默认超时:
{
"DatabaseConfiguration": {
"DefaultCommandTimeoutSeconds": 30,
"ConnectionTimeoutSeconds": 15,
"MaxConcurrentSessions": 10,
"SessionCleanupIntervalMinutes": 60,
"TotalToolCallTimeoutSeconds": 120,
"MaxCellOutputLength": 40
}
}
超时设置:
DefaultCommandTimeoutSeconds:SQL 命令执行的默认超时时间(默认:30 秒)ConnectionTimeoutSeconds:建立 SQL 连接的超时时间(默认:15 秒)MaxConcurrentSessions:并发查询会话的最大数量(默认:10)SessionCleanupIntervalMinutes:清理已完成会话的间隔(默认:60 分钟)TotalToolCallTimeoutSeconds:工具调用完成所允许的最长时间(默认:120 秒,设为 null 可禁用)MaxCellOutputLength:查询结果中每个单元格显示的最大字符数。超过此长度的内容会被截断并以...结尾。设为0可禁用截断(默认:40)
也可以通过环境变量设置这些值:
# Docker example
docker run \
-e "DatabaseConfiguration__DefaultCommandTimeoutSeconds=60" \
-e "DatabaseConfiguration__ConnectionTimeoutSeconds=30" \
-e "DatabaseConfiguration__TotalToolCallTimeoutSeconds=180" \
-e "MSSQL_CONNECTIONSTRING=Server=your_server;..." \
aadversteeg/mssqlclient-mcp-server:latest
# Claude Desktop configuration
"mssql": {
"command": "docker",
"args": ["run", "--rm", "-i",
"-e", "DatabaseConfiguration__DefaultCommandTimeoutSeconds=60",
"-e", "DatabaseConfiguration__ConnectionTimeoutSeconds=30",
"-e", "DatabaseConfiguration__TotalToolCallTimeoutSeconds=180",
"-e", "MSSQL_CONNECTIONSTRING=Server=your_server;...",
"aadversteeg/mssqlclient-mcp-server:latest"
]
}
工具调用超时管理
TotalToolCallTimeoutSeconds 设置提供了一种安全机制,可防止工具无限期运行:
工作原理:
- 为任何单次工具调用设置最长完成时间
- 超时后,操作会被取消,并显示清晰的超时错误消息
- 有助于防止操作挂起,并确保响应迅速
- 与各项操作的超时设置配合使用,实现精细控制
配置注意事项:
- MCP 客户端限制:大多数 MCP 客户端(如 Claude Desktop)的连接超时时间为 2-5 分钟
- 最佳实践:将
TotalToolCallTimeoutSeconds设为低于客户端超时时间,以获得最佳用户体验(通常为 90-120 秒) - 长时间运行的操作:对于需要更多时间的操作,请使用基于会话的工具(
start_query、start_stored_procedure) - 按需禁用:设为
null可禁用总超时限制
配置示例:
{
"TotalToolCallTimeoutSeconds": 90, // 1.5 minutes - good for most operations
"DefaultCommandTimeoutSeconds": 30 // Default timeout for individual SQL commands
}
此配置可确保:
- 工具调用的总运行时间不超过 90 秒
- 单条 SQL 命令的默认超时时间为 30 秒
- 长时间运行的操作应改用基于会话的工具
运行时超时管理
该服务提供了可动态管理超时的工具:
get_command_timeout
返回当前超时配置设置。
请求示例:
{
"name": "get_command_timeout",
"parameters": {}
}
响应示例:
{
"defaultCommandTimeoutSeconds": 30,
"connectionTimeoutSeconds": 15,
"maxConcurrentSessions": 10,
"sessionCleanupIntervalMinutes": 60,
"totalToolCallTimeoutSeconds": 120,
"timestamp": "2024-12-19 10:30:45 UTC"
}
set_command_timeout
更新所有新操作的默认命令超时时间。现有操作继续使用原有超时时间。
参数:
timeoutSeconds(必需):新的超时时间(秒)(1-3600)
请求示例:
{
"name": "set_command_timeout",
"parameters": {
"timeoutSeconds": 120
}
}
响应示例:
{
"message": "Default command timeout updated successfully",
"oldTimeoutSeconds": 30,
"newTimeoutSeconds": 120,
"note": "This change only affects new operations. Existing sessions will continue with their original timeout settings.",
"timestamp": "2024-12-19 10:31:00 UTC"
}
单项操作超时
大多数数据库操作都支持可选的 timeoutSeconds 参数,可覆盖该项操作的默认超时时间:
// Long-running query with 5-minute timeout
{
"name": "execute_query",
"parameters": {
"query": "SELECT * FROM LargeTable WITH (NOLOCK)",
"timeoutSeconds": 300
}
}
// Complex stored procedure with 10-minute timeout
{
"name": "execute_stored_procedure",
"parameters": {
"procedureName": "GenerateMonthlyReport",
"parameters": "{}",
"timeoutSeconds": 600
}
}
// Quick table list with 10-second timeout
{
"name": "list_tables",
"parameters": {
"timeoutSeconds": 10
}
}
支持单项操作超时的工具:
- 所有查询执行工具(
execute_query、execute_query_in_database) - 所有存储过程工具(
execute_stored_procedure、execute_stored_procedure_in_database、get_stored_procedure_parameters) - 所有架构发现工具(
list_tables、get_table_schema、list_stored_procedures) - 会话管理工具(
start_query、start_stored_procedure、start_query_in_database、start_stored_procedure_in_database)
最佳实践
- 默认配置:根据典型工作负载,在
appsettings.json中设置合理的默认值 - 总超时:将
TotalToolCallTimeoutSeconds设置为 90-120 秒,以获得最佳 MCP 客户端兼容性 - 长时间运行的操作:为已知会长时间运行的查询或过程设置单独的操作超时
- 动态调整:在一天中工作负载有所变化时,使用
set_command_timeout - 监控:在运行关键操作前,使用
get_command_timeout验证当前设置 - 后台操作:对于超出超时限制的操作,请使用基于会话的工具:
- 对于长时间运行的查询,使用
start_query/start_query_in_database - 对于长时间运行的过程,使用
start_stored_procedure/start_stored_procedure_in_database - 使用
get_session_status监控进度 - 使用
get_session_results获取结果 - 需要时使用
stop_session取消 - 这些工具绕过
TotalToolCallTimeoutSeconds限制,在后台运行
- 对于长时间运行的查询,使用
超时限制
- 命令超时:1-3600 秒(最长 1 小时)
- 连接超时:仅在启动时配置(运行期间不可更改)
- 单个操作覆盖值:始终优先于默认设置
数据库连接字符串
连接数据库需要 SQL Server 连接字符串。此连接字符串应包含服务器信息、身份验证详细信息以及任何必需的连接选项。
可以使用 MSSQL_CONNECTIONSTRING 环境变量设置连接字符串:
# Database Mode with all execution types enabled
docker run \
-e "DatabaseConfiguration__EnableExecuteQuery=true" \
-e "DatabaseConfiguration__EnableExecuteStoredProcedure=true" \
-e "DatabaseConfiguration__EnableStartQuery=true" \
-e "DatabaseConfiguration__EnableStartStoredProcedure=true" \
-e "MSSQL_CONNECTIONSTRING=Server=your_server;Database=your_db;User Id=your_user;Password=your_password;TrustServerCertificate=True;" \
aadversteeg/mssqlclient-mcp-server:latest
# Server Mode with all execution types enabled
docker run \
-e "DatabaseConfiguration__EnableExecuteQuery=true" \
-e "DatabaseConfiguration__EnableExecuteStoredProcedure=true" \
-e "DatabaseConfiguration__EnableStartQuery=true" \
-e "DatabaseConfiguration__EnableStartStoredProcedure=true" \
-e "MSSQL_CONNECTIONSTRING=Server=your_server;User Id=your_user;Password=your_password;TrustServerCertificate=True;" \
aadversteeg/mssqlclient-mcp-server:latest
服务器模式与数据库模式
MCP 服务会根据连接字符串自动检测模式:
- 服务器模式:连接字符串中未指定数据库(没有
Database=或Initial Catalog=参数) - 数据库模式:连接字符串中指定了特定数据库
连接字符串示例:
# Database Mode - Connects to specific database
Server=database.example.com;Database=Northwind;User Id=sa;Password=YourPassword;TrustServerCertificate=True;
# Server Mode - No specific database
Server=database.example.com;User Id=sa;Password=YourPassword;TrustServerCertificate=True;
# Database Mode with Windows Authentication
Server=database.example.com;Database=Northwind;Integrated Security=SSPI;TrustServerCertificate=True;
# Server Mode with specific port
Server=database.example.com,1433;User Id=sa;Password=YourPassword;TrustServerCertificate=True;
如果未提供连接字符串,尝试使用工具时,服务将返回错误消息。
**注意:**在 Docker 容器中运行时,不支持集成安全性(Windows 身份验证)。请改用 SQL Server 身份验证。
使用 Docker
无需 .NET 10 SDK。
"mssql": {
"command": "docker",
"args": [
"run",
"--rm",
"-i",
"-e", "MSSQL_CONNECTIONSTRING=Server=your_server;Database=your_db;User Id=your_user;Password=your_password;TrustServerCertificate=True;",
"-e", "DatabaseConfiguration__EnableExecuteQuery=true",
"-e", "DatabaseConfiguration__EnableExecuteStoredProcedure=true",
"-e", "DatabaseConfiguration__EnableStartQuery=true",
"-e", "DatabaseConfiguration__EnableStartStoredProcedure=true",
"aadversteeg/mssqlclient-mcp-server:latest"
]
}
**面向使用本地 SQL Server 的 Windows 用户的注意事项:**在 Windows 上使用 Docker Desktop 连接本地 SQL Server 实例时,请确保在 SQL Server Configuration Manager(SQL Server Network Configuration → Protocols for MSSQLSERVER → TCP/IP)中启用了 TCP/IP,并且 SQL Server 已配置为侦听端口 1433(TCP/IP Properties → IP Addresses → IPAll → TCP Port: 1433)。完成这些更改后,重启 SQL Server 服务。
架构
接口设计
该服务采用三层接口架构,实现清晰的关注点分离:
-
IDatabaseService(核心层)
- 不带超时上下文的底层数据库操作
- 直接与 SQL Server 通信
- 连接和命令管理
-
IServerDatabase(服务器模式层)
- 跨数据库的服务器级操作
- 包含超时上下文管理
- 数据库切换和跨数据库查询
-
IDatabaseContext(数据库模式层)
- 限定于数据库范围的操作
- 适用于单数据库场景的简化接口
- 包含超时上下文管理
超时管理
该服务使用统一的超时管理系统:
- ToolCallTimeoutContext:所有高级接口中的可空参数
- 简化的 API:使用带有可选超时上下文的单一方法签名
- 简洁的设计:不重载方法;可空参数提供灵活性
- 一致的错误处理:标准化错误格式:
"Error: SQL error while {operation}: {message}"
类型系统
服务器包含一套复杂的类型映射系统,可根据存储过程参数元数据将 JSON 值转换为适当的 SQL Server 类型:
- 自动类型检测:使用 SQL Server 的
sys.parameters元数据作为权威来源 - 丰富的类型支持:支持所有主要的 SQL Server 数据类型,包括 varchar、nvarchar、int、decimal、datetime、uniqueidentifier 等
- 验证:针对类型不匹配和约束违规提供详细的错误消息
- 默认值:支持带默认值的参数和可选参数
参数处理
- 不区分大小写:参数名称匹配时不区分大小写
- 灵活的命名方式:支持
@ParameterName和ParameterName两种格式 - 规范化:自动规范化和验证参数名称
- JSON Schema:生成兼容 JSON Schema 的输出,用于参数验证
安全模型
服务器采用多层安全方案:
- 工具级安全:可通过配置启用或禁用单个工具
- 参数验证:根据 SQL Server 元数据验证所有输入
- SQL 注入防护:全程使用参数化查询
- 连接安全:支持所有 SQL Server 身份验证方式
技术栈
- 框架:.NET 10.0 和 C# 14
- 语言功能:可空引用类型、async/await、记录类型
- 数据库访问:Microsoft.Data.SqlClient
- MCP SDK:Model Context Protocol C# SDK
- 测试:使用 Moq 进行全面单元测试的 xUnit
- 容器化:用于优化镜像的多阶段 Docker 构建
许可证
本项目采用 MIT 许可证授权,详情请参阅 LICENSE 文件。
评论
一个开放协议,规定了 AI 应用如何以统一方式连接外部工具与数据源。客户端负责与模型对话,MCP 服务负责提供工具、资源和提示模板,两者通过标准消息通信,同一个服务可以被不同客户端复用。