关于 Mcp Cosmosdb Sql
Mcp Cosmosdb Sql 为使用 Azure CosmosDB 的开发者和数据分析人员提供数据库操作 MCP 服务,支持多个连接、容器分析、SQL 查询及文档 CRUD。写操作默认关闭,并可按连接配置权限。
主要功能
- 01管理多个 CosmosDB 连接
- 02发现数据库和容器
- 03查询容器定义、统计及模式
- 04执行带参数的 SQL 查询
- 05读取和筛选文档
- 06受控执行文档 CRUD
适用场景
- 01检查容器结构和统计信息
- 02分析文档模式
- 03查询或筛选 CosmosDB 数据
- 04在启用写权限后维护文档
MCP 相关
该 MCP 服务向客户端提供连接管理、数据库和容器检查、查询、文档读取及 CRUD 工具。文档写操作默认禁用,可按连接启用。
配置
本地服务的配置在各客户端中通用,复制后粘贴到客户端的 MCP 配置文件即可。
工具
本地服务需要在你的电脑上运行后才能读取工具,维护者暂未提供工具列表。
详细介绍
MCP CosmosDB - Azure CosmosDB MCP 服务
一款功能全面的 Model Context Protocol(MCP) 服务,用于执行 Azure CosmosDB 数据库操作。此服务通过 MCP 协议提供 13 种强大工具,用于文档数据库分析、容器发现、数据查询和 CRUD 操作。
✨ 功能特性
- 🔗 多连接支持:可通过单个 MCP 实例管理多个 CosmosDB 帐户/数据库
- 🔒 安全优先:默认禁用写入操作
- ⚡ 高性能:连接缓存和优化查询
- 📊 13 种工具:完整的数据库操作工具集
🚀 快速开始
前提条件
- Node.js 18+ 和 npm
- Azure CosmosDB 数据库及其连接字符串
- 兼容 MCP 的客户端(Claude Desktop、Cursor IDE 等)
⚙️ 配置
配置优先级
此服务支持三种配置方法(按优先级排序):
| 优先级 | 方法 | 环境变量 | 描述 |
|---|---|---|---|
| 1️⃣ | 外部文件 | COSMOS_CONNECTIONS_FILE | 包含连接数组的 JSON 文件路径 |
| 2️⃣ | JSON 字符串 | COSMOS_CONNECTIONS | 内联 JSON 连接数组 |
| 3️⃣ | 单个连接 | COSMOS_CONNECTION_STRING + COSMOS_DATABASE_ID | 旧版单连接模式 |
🔒 安全配置
| 变量 | 描述 | 默认值 |
|---|---|---|
DB_ALLOW_MODIFICATIONS | 启用/禁用写入操作(创建、更新、删除、插入或更新) | false |
⚠️ 重要:为确保安全,默认情况下会禁用所有写入操作。只有在需要执行写入操作时,才设置
DB_ALLOW_MODIFICATIONS=true。
📦 安装选项
选项 1:使用外部文件进行多连接配置(推荐)✅
创建连接文件(例如 cosmos-connections.json):
[
{
"id": "production",
"connectionString": "AccountEndpoint=https://myapp-prod.documents.azure.com:443/;AccountKey=...;",
"databaseId": "ProductionDB",
"allowModifications": false,
"description": "Production database (read-only)"
},
{
"id": "development",
"connectionString": "AccountEndpoint=https://myapp-dev.documents.azure.com:443/;AccountKey=...;",
"databaseId": "DevDB",
"allowModifications": true,
"description": "Development database"
},
{
"id": "analytics",
"connectionString": "AccountEndpoint=https://analytics.documents.azure.com:443/;AccountKey=...;",
"databaseId": "AnalyticsDB",
"allowModifications": false,
"description": "Analytics database"
}
]
配置 MCP 客户端:
{
"mcpServers": {
"cosmosdb": {
"command": "npx",
"args": ["-y", "mcpcosmosdb@latest"],
"env": {
"COSMOS_CONNECTIONS_FILE": "/path/to/cosmos-connections.json"
}
}
}
}
选项 2:使用内联 JSON 进行多连接配置
{
"mcpServers": {
"cosmosdb": {
"command": "npx",
"args": ["-y", "mcpcosmosdb@latest"],
"env": {
"COSMOS_CONNECTIONS": "[{\"id\":\"prod\",\"connectionString\":\"AccountEndpoint=https://...\",\"databaseId\":\"ProdDB\",\"allowModifications\":false},{\"id\":\"dev\",\"connectionString\":\"AccountEndpoint=https://...\",\"databaseId\":\"DevDB\",\"allowModifications\":true}]"
}
}
}
}
选项 3:单个连接(旧版)
只读模式(默认 — 安全):
{
"mcpServers": {
"cosmosdb": {
"command": "npx",
"args": ["-y", "mcpcosmosdb@latest"],
"env": {
"COSMOS_CONNECTION_STRING": "AccountEndpoint=https://your-cosmos-account.documents.azure.com:443/;AccountKey=your-account-key-here;",
"COSMOS_DATABASE_ID": "your-database-name"
}
}
}
}
启用写入操作:
{
"mcpServers": {
"cosmosdb": {
"command": "npx",
"args": ["-y", "mcpcosmosdb@latest"],
"env": {
"COSMOS_CONNECTION_STRING": "AccountEndpoint=https://your-cosmos-account.documents.azure.com:443/;AccountKey=your-account-key-here;",
"COSMOS_DATABASE_ID": "your-database-name",
"DB_ALLOW_MODIFICATIONS": "true"
}
}
}
}
选项 4:使用 GitHub 上的 NPX
{
"mcpServers": {
"cosmosdb": {
"command": "npx",
"args": ["-y", "hendrickcastro/MCPCosmosDB"],
"env": {
"COSMOS_CONNECTION_STRING": "AccountEndpoint=https://...;AccountKey=...;",
"COSMOS_DATABASE_ID": "your-database-name"
}
}
}
}
选项 5:本地开发
git clone https://github.com/hendrickcastro/MCPCosmosDB.git
cd MCPCosmosDB
npm install && npm run build
{
"mcpServers": {
"cosmosdb": {
"command": "node",
"args": ["path/to/MCPCosmosDB/dist/server.js"],
"env": {
"COSMOS_CONNECTIONS_FILE": "/path/to/cosmos-connections.json"
}
}
}
}
🛠️ 可用工具(共 13 种)
🔗 连接管理
| 工具 | 描述 |
|---|---|
mcp_list_connections | 列出所有已配置的连接及其状态 |
📖 读取操作(始终可用)
| 工具 | 描述 |
|---|---|
mcp_list_databases | 列出 CosmosDB 帐户中的所有数据库 |
mcp_list_containers | 列出当前数据库中的所有容器 |
mcp_get_container_definition | 获取详细的容器配置(分区键、索引策略、吞吐量) |
mcp_get_container_stats | 获取容器统计信息(文档数、大小、分区分布) |
mcp_cosmos_query | 执行带参数和性能指标的 SQL 查询 |
mcp_get_documents | 获取文档,可选择进行筛选 |
mcp_get_document_by_id | 根据 ID 和分区键获取特定文档 |
mcp_analyze_schema | 分析容器中的文档架构结构 |
✏️ 写入操作(需要 allowModifications: true)
| 工具 | 描述 |
|---|---|
mcp_create_document | 在容器中创建新文档 |
mcp_update_document | 更新(替换)现有文档 |
mcp_delete_document | 从容器中删除文档 |
mcp_upsert_document | 创建或更新文档(upsert 操作) |
🛡️ 安全提示:默认情况下会阻止写入操作。在连接配置中设置
allowModifications: true,或在单连接模式下设置DB_ALLOW_MODIFICATIONS=true。
📋 使用示例
多连接用法
// List all available connections
const connections = await mcp_list_connections();
// Returns: { connections: [{id: "prod", databaseId: "ProdDB", isConnected: true}, ...] }
// Query specific connection using connection_id
const prodData = await mcp_cosmos_query({
connection_id: "production",
container_id: "users",
query: "SELECT TOP 10 c.id, c.name FROM c ORDER BY c._ts DESC"
});
const devData = await mcp_cosmos_query({
connection_id: "development",
container_id: "users",
query: "SELECT TOP 10 c.id, c.name FROM c ORDER BY c._ts DESC"
});
容器分析
// List all containers (uses default connection if connection_id not specified)
const containers = await mcp_list_containers({
connection_id: "production"
});
// Get container definition
const containerDef = await mcp_get_container_definition({
connection_id: "production",
container_id: "users"
});
// Get container statistics
const stats = await mcp_get_container_stats({
connection_id: "production",
container_id: "users",
sample_size: 1000
});
查询数据
⚠️ 重要:始终使用 TOP N 并指定字段。切勿使用 SELECT *——这会导致大型容器中的请求超时和 RU 消耗过高。
// ✅ CORRECT: Using TOP and specific fields
const result = await mcp_cosmos_query({
connection_id: "production",
container_id: "products",
query: "SELECT TOP 50 c.id, c.name, c.price FROM c WHERE c.category = @category",
parameters: { category: "electronics" }
});
// ❌ WRONG: SELECT * without TOP (will timeout on large containers)
// query: "SELECT * FROM c WHERE c.category = @category"
// Get documents with simple filters
const documents = await mcp_get_documents({
connection_id: "production",
container_id: "orders",
filter_conditions: { status: "completed" },
order_by: "_ts",
order_direction: "DESC",
limit: 100
});
文档操作
// Get specific document by ID
const document = await mcp_get_document_by_id({
connection_id: "production",
container_id: "users",
document_id: "user-123",
partition_key: "user-123"
});
// Analyze schema
const schema = await mcp_analyze_schema({
connection_id: "production",
container_id: "products",
sample_size: 500
});
CRUD 操作(需要 allowModifications: true)
// Create a new document
const created = await mcp_create_document({
connection_id: "development", // Use a connection with write access
container_id: "users",
document: {
id: "user-456",
email: "[email protected]",
name: "John Doe",
status: "active"
},
partition_key: "user-456"
});
// Update a document (full replacement)
const updated = await mcp_update_document({
connection_id: "development",
container_id: "users",
document_id: "user-456",
document: {
id: "user-456",
email: "[email protected]",
name: "John Doe",
status: "inactive"
},
partition_key: "user-456"
});
// Upsert a document (create or update)
const upserted = await mcp_upsert_document({
connection_id: "development",
container_id: "users",
document: {
id: "user-789",
email: "[email protected]",
name: "Jane Doe"
},
partition_key: "user-789"
});
// Delete a document
const deleted = await mcp_delete_document({
connection_id: "development",
container_id: "users",
document_id: "user-456",
partition_key: "user-456"
});
🔧 连接文件架构
interface ConnectionConfig {
id: string; // Unique identifier for the connection
connectionString: string; // CosmosDB connection string
databaseId: string; // Database ID to connect to
allowModifications?: boolean; // Enable write operations (default: false)
description?: string; // Optional description
}
cosmos-connections.json 示例:
[
{
"id": "athlete",
"connectionString": "AccountEndpoint=https://dbsqlcosmosathlete.documents.azure.com:443/;AccountKey=...;",
"databaseId": "data",
"allowModifications": false,
"description": "Athlete data"
},
{
"id": "events",
"connectionString": "AccountEndpoint=https://dbsqlcosmosevents.documents.azure.com:443/;AccountKey=...;",
"databaseId": "events",
"allowModifications": false,
"description": "Events data"
}
]
🚨 故障排除
连接问题:
- 连接字符串无效:确认连接字符串格式包含 AccountEndpoint 和 AccountKey
- 找不到数据库:检查 databaseId 是否与现有数据库匹配
- 请求超时:增大 COSMOS_MAX_RETRY_WAIT_TIME 或检查网络
查询问题:
- 查询超时:使用
TOP N限制结果,只指定需要的字段,避免使用SELECT * - 需要跨分区查询:在查询参数中设置
enable_cross_partition: true - 需要分区键:为单分区操作指定 partition_key
多连接问题:
- 找不到连接:使用
mcp_list_connections查看可用的连接 ID - 数据库错误:确认
connection_id参数指向正确的连接
写入操作被阻止:
- 错误:“Database modifications are disabled”:在连接配置中设置
allowModifications: true,或设置DB_ALLOW_MODIFICATIONS=true - 这是一项安全功能——默认情况下会禁用写入操作
CosmosDB Emulator:
- 安装 Azure CosmosDB Emulator
- 在端口 8081 上启动模拟器
- 使用默认的模拟器连接字符串
- 创建数据库和容器以进行测试
🧪 开发
npm test # Run tests
npm run build # Build project
npm start # Development mode
🏗️ 架构
项目结构:
src/
├── tools/ # Tool implementations
│ ├── containerAnalysis.ts # Container operations
│ ├── dataOperations.ts # Data queries & CRUD
│ └── types.ts # Type definitions
├── db.ts # CosmosDB connection & multi-connection management
├── server.ts # MCP server setup
└── tools.ts # Tool definitions
主要功能:
- ⚡ 连接缓存和连接池
- 🔗 多连接管理
- 🛡️ 全面的错误处理
- 🔒 按连接保护写入操作
- 📊 性能指标和请求费用
- 🔧 灵活的配置选项
- 📋 智能架构分析
📝 重要说明
- 查询最佳实践:始终使用
TOP N并指定字段,切勿使用SELECT * - 容器 ID:使用 CosmosDB 中的确切名称
- 分区键:对优化性能和 CRUD 操作至关重要
- 跨分区查询:可能成本较高,请使用筛选条件
- 请求费用:监控 RU 消耗
- 安全性:安全存储连接字符串(使用外部文件)
- 写保护:仅对需要写入的连接启用
🤝 参与贡献
- Fork 此仓库
- 创建功能分支(
git checkout -b feature/name) - 进行更改并添加测试
- 确保测试通过(
npm test) - 提交更改(
git commit -m 'Add feature') - 推送并发起 Pull Request
📄 许可证
MIT 许可证,详情请参阅 LICENSE 文件。
🏷️ 标签和关键词
数据库: cosmosdb azure-cosmosdb nosql document-database database-analysis database-tools azure database-management database-operations data-analysis multi-database
MCP 和 AI: model-context-protocol mcp-server mcp-tools ai-tools claude-desktop cursor-ide anthropic llm-integration ai-database intelligent-database
技术: typescript nodejs npm-package cli-tool database-client nosql-client database-sdk rest-api json-api database-connector
功能: container-analysis document-operations sql-queries schema-analysis query-execution database-search data-exploration database-insights partition-management throughput-analysis crud-operations document-crud multi-connection
使用场景: database-development data-science business-intelligence database-migration schema-documentation performance-analysis data-governance database-monitoring troubleshooting automation
🙏 致谢
🎯 MCP CosmosDB 通过 Model Context Protocol 提供全面的 Azure CosmosDB 数据库分析。非常适合使用 CosmosDB 的开发者和数据分析师! 🚀
评论
一个开放协议,规定了 AI 应用如何以统一方式连接外部工具与数据源。客户端负责与模型对话,MCP 服务负责提供工具、资源和提示模板,两者通过标准消息通信,同一个服务可以被不同客户端复用。