MCP CosmosDB
The MCP CosmosDB server enables comprehensive management and analysis of Azure CosmosDB databases through the Model Context Protocol, providing 8 key tools:
• List Databases - Enumerate all databases in your CosmosDB account • List Containers - Display all containers within a database • Container Information - Get detailed metadata including partition key, indexing policy, and throughput settings • Container Statistics - Analyze document count, estimated size, and partition key distribution • Execute SQL Queries - Run custom SQL queries with parameters, result limits, and cross-partition support • Get Documents - Retrieve documents with filtering, partition key specification, and result limiting • Get Document by ID - Fetch specific documents using their unique ID and partition key • Schema Analysis - Examine document structure and data types to identify patterns and anomalies
Allows direct execution from GitHub repository using npx, with configuration instructions for connecting to various MCP clients.
Leverages Node.js runtime for server operations, requiring Node.js 18+ for execution and compatibility.
Built with TypeScript for type safety and modern JavaScript features, providing strongly-typed interfaces for database operations.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@MCP CosmosDB show me the top 10 products by price from the products container"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
MCP CosmosDB - Azure CosmosDB MCP Server
A comprehensive Model Context Protocol (MCP) server for Azure CosmosDB database operations. This server provides 13 powerful tools for document database analysis, container discovery, data querying, and CRUD operations through the MCP protocol.
✨ Features
🔗 Multi-Connection Support: Manage multiple CosmosDB accounts/databases from a single MCP instance
🔒 Security First: Write operations disabled by default
⚡ High Performance: Connection caching and optimized queries
📊 13 Tools: Complete set of database operations
Related MCP server: Filesystem MCP Server
🚀 Quick Start
Prerequisites
Node.js 18+ and npm
Azure CosmosDB database with connection string
MCP-compatible client (Claude Desktop, Cursor IDE, etc.)
⚙️ Configuration
Configuration Priority
The server supports three configuration methods (in order of priority):
Priority | Method | Environment Variable | Description |
1️⃣ | External File |
| Path to JSON file with connections array |
2️⃣ | JSON String |
| Inline JSON array of connections |
3️⃣ | Single Connection |
| Legacy single connection mode |
🔒 Security Configuration
Variable | Description | Default |
| Enable/disable write operations (create, update, delete, upsert) |
|
⚠️ IMPORTANT: By default, all write operations are DISABLED for safety. Set
DB_ALLOW_MODIFICATIONS=trueonly when you need to perform write operations.
📦 Installation Options
Option 1: Multi-Connection with External File (Recommended) ✅
Create a connections file (e.g., 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"
}
]Configure your MCP client:
{
"mcpServers": {
"cosmosdb": {
"command": "npx",
"args": ["-y", "mcpcosmosdb@latest"],
"env": {
"COSMOS_CONNECTIONS_FILE": "/path/to/cosmos-connections.json"
}
}
}
}Option 2: Multi-Connection with Inline 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}]"
}
}
}
}Option 3: Single Connection (Legacy)
Read-Only Mode (Default - Safe):
{
"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"
}
}
}
}With Write Operations Enabled:
{
"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"
}
}
}
}Option 4: NPX from GitHub
{
"mcpServers": {
"cosmosdb": {
"command": "npx",
"args": ["-y", "hendrickcastro/MCPCosmosDB"],
"env": {
"COSMOS_CONNECTION_STRING": "AccountEndpoint=https://...;AccountKey=...;",
"COSMOS_DATABASE_ID": "your-database-name"
}
}
}
}Option 5: Local Development
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"
}
}
}
}🛠️ Available Tools (13 Total)
🔗 Connection Management
Tool | Description |
| List all configured connections with their status |
📖 Read Operations (Always Available)
Tool | Description |
| List all databases in the CosmosDB account |
| List all containers in the current database |
| Get detailed container configuration (partition key, indexing policy, throughput) |
| Get container statistics (document count, size, partition distribution) |
| Execute SQL queries with parameters and performance metrics |
| Retrieve documents with optional filtering |
| Get a specific document by ID and partition key |
| Analyze document schema structure in containers |
✏️ Write Operations (Require allowModifications: true)
Tool | Description |
| Create a new document in a container |
| Update (replace) an existing document |
| Delete a document from a container |
| Create or update a document (upsert operation) |
🛡️ Security Note: Write operations are blocked by default. Set
allowModifications: truein the connection config orDB_ALLOW_MODIFICATIONS=truefor single connection mode.
📋 Usage Examples
Multi-Connection Usage
// 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"
});Container Analysis
// 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
});Querying Data
⚠️ IMPORTANT: Always use TOP N and specify fields. NEVER use SELECT * - it causes timeouts and high RU consumption in large containers.
// ✅ 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
});Document Operations
// 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 Operations (Requires 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: "user@example.com",
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: "newemail@example.com",
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: "another@example.com",
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"
});🔧 Connection File Schema
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
}Example 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"
}
]🚨 Troubleshooting
Connection Issues:
Invalid connection string: Verify connection string format includes AccountEndpoint and AccountKey
Database not found: Check databaseId matches existing database
Request timeout: Increase COSMOS_MAX_RETRY_WAIT_TIME or check network
Query Issues:
Query timeout: Use
TOP Nto limit results, specify only needed fields, avoidSELECT *Cross partition query required: Set
enable_cross_partition: truein query parametersPartition key required: Specify partition_key for single-partition operations
Multi-Connection Issues:
Connection not found: Use
mcp_list_connectionsto see available connection IDsWrong database: Verify the
connection_idparameter points to the correct connection
Write Operation Blocked:
Error: "Database modifications are disabled": Set
allowModifications: truein connection config orDB_ALLOW_MODIFICATIONS=trueThis is a safety feature - write operations are disabled by default
CosmosDB Emulator:
Install Azure CosmosDB Emulator
Start emulator on port 8081
Use default emulator connection string
Create database and containers for testing
🧪 Development
npm test # Run tests
npm run build # Build project
npm start # Development mode🏗️ Architecture
Project Structure:
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 definitionsKey Features:
⚡ Connection caching and pooling
🔗 Multi-connection management
🛡️ Comprehensive error handling
🔒 Write operation protection per connection
📊 Performance metrics and request charges
🔧 Flexible configuration options
📋 Intelligent schema analysis
📝 Important Notes
Query Best Practices: Always use
TOP Nand specify fields - never useSELECT *Container IDs: Use exact names as in CosmosDB
Partition Keys: Required for optimal performance and CRUD operations
Cross-Partition Queries: Can be expensive; use filters
Request Charges: Monitor RU consumption
Security: Store connection strings securely (use external file)
Write Protection: Enable only for connections that need it
🤝 Contributing
Fork the repository
Create feature branch (
git checkout -b feature/name)Make changes and add tests
Ensure tests pass (
npm test)Commit changes (
git commit -m 'Add feature')Push and open Pull Request
📄 License
MIT License - see LICENSE file for details.
🏷️ Tags & Keywords
Database: 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
Technology: typescript nodejs npm-package cli-tool database-client nosql-client database-sdk rest-api json-api database-connector
Features: 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
Use Cases: database-development data-science business-intelligence database-migration schema-documentation performance-analysis data-governance database-monitoring troubleshooting automation
🙏 Acknowledgments
Inspired by MCPQL
🎯 MCP CosmosDB provides comprehensive Azure CosmosDB database analysis through the Model Context Protocol. Perfect for developers and data analysts working with CosmosDB! 🚀
Available Tools
13 toolsmcp_analyze_schemaA
Analyze the schema/structure of documents in a container. Samples documents to discover field names, data types, and frequency. Use this to understand the data model before writing queries.
Inputs: container_id (required), sample_size, connection_id.
mcp_cosmos_queryA
Execute a CosmosDB SQL query against a container. Use this for complex queries with JOINs, aggregations, or custom SQL syntax.
⚠️ IMPORTANT - AVOID SELECT *:
NEVER use SELECT * in large containers - it causes timeouts and high RU consumption
ALWAYS use TOP N to limit results: SELECT TOP 10 c.id, c.name FROM c
ALWAYS specify only the fields you need: SELECT c.id, c.name, c.email FROM c
COSMOSDB SQL SYNTAX EXAMPLES:
Basic: SELECT TOP 10 c.id, c.name FROM c WHERE c.status = @status
With projection: SELECT c.id, c.name, c.email FROM c
Aggregation: SELECT VALUE COUNT(1) FROM c
Array contains: SELECT TOP 20 c.id FROM c WHERE ARRAY_CONTAINS(c.tags, 'urgent')
Nested: SELECT TOP 10 c.id, c.address FROM c WHERE c.address.city = 'Madrid'
ORDER BY: SELECT TOP 10 c.id, c._ts FROM c ORDER BY c._ts DESC
PARAMETERS: Use @paramName syntax and provide values in the 'parameters' object. Example: query="SELECT TOP 10 c.id, c.type FROM c WHERE c.type = @type", parameters={type: "order"}
Inputs: container_id (required), query (required), parameters, max_items, +2 more.
mcp_create_documentB
Create a new document in a CosmosDB container.
REQUIREMENTS:
The document MUST have an 'id' field (string)
The document MUST have the partition key field with a value
The 'id' must be unique within the partition
Example: mcp_create_document({ container_id: 'users', document: {id: 'user-456', email: 'test@example.com', status: 'active'}, partition_key: 'user-456', connection_id: 'athlete' })
Inputs: container_id (required), document (required), partition_key (required), connection_id.
mcp_delete_documentA
Delete a document from a CosmosDB container.
WARNING: This operation is irreversible. The document will be permanently deleted.
Example: mcp_delete_document({ container_id: 'users', document_id: 'user-456', partition_key: 'user-456', connection_id: 'athlete' })
Inputs: container_id (required), document_id (required), partition_key (required), connection_id.
mcp_get_container_definitionA
Get detailed configuration of a specific container including partition key, indexing policy, and throughput settings. Use this to understand the container structure before writing queries. Example: mcp_get_container_definition({container_id: 'users', connection_id: 'athlete'})
Inputs: container_id (required), connection_id.
mcp_get_container_statsA
Get statistical information about a container including document count, estimated size, and partition key distribution. Use this for capacity planning and performance analysis. Example: mcp_get_container_stats({container_id: 'orders', sample_size: 500})
Inputs: container_id (required), sample_size, connection_id.
mcp_get_document_by_idA
Get a single document by its ID and partition key. This is the most efficient way to retrieve a specific document.
IMPORTANT: Both document_id and partition_key are required for a point read in CosmosDB. The partition_key type must match your container's partition key type.
Example: mcp_get_document_by_id({container_id: 'users', document_id: 'user-123', partition_key: 'user-123', connection_id: 'athlete'})
Inputs: container_id (required), document_id (required), partition_key (required), connection_id.
mcp_get_documentsA
Get documents from a container with simple filters and ordering. Use this for basic queries without complex SQL syntax.
FOR COMPLEX QUERIES: Use mcp_cosmos_query instead. THIS TOOL IS BEST FOR:
Getting all documents (with limit)
Simple equality filters on fields
Filtering by partition key for performance
Getting the most recent or oldest documents using order_by
Example: mcp_get_documents({container_id: 'users', limit: 10, order_by: '_ts', order_direction: 'DESC', connection_id: 'athlete'}) Example: mcp_get_documents({container_id: 'users', limit: 50, filter_conditions: {status: 'active'}})
Inputs: container_id (required), limit, partition_key, filter_conditions, +3 more.
mcp_list_connectionsA
List all available CosmosDB connections configured in this MCP server. Use this to discover which connection_id values you can use. Each connection points to a different CosmosDB account/database.
Inputs: no named parameters.
mcp_list_containersA
List all containers in the connected CosmosDB database. Use this to discover available containers and their partition key configurations before querying data. Returns container IDs, partition key paths, and indexing policies.
Inputs: connection_id.
mcp_list_databasesA
List all databases in the CosmosDB account. Use this to discover available databases before querying containers. Returns database IDs, timestamps, and ETags.
Inputs: connection_id.
mcp_update_documentA
Update (replace) an existing document in a CosmosDB container.
NOTE: This performs a full document replacement. Include ALL fields you want to keep. For partial updates, first get the document with mcp_get_document_by_id, modify it, then update.
Example: mcp_update_document({ container_id: 'users', document_id: 'user-456', document: {id: 'user-456', email: 'new@example.com', status: 'inactive'}, partition_key: 'user-456', connection_id: 'athlete' })
Inputs: container_id (required), document_id (required), document (required), partition_key (required), +1 more.
mcp_upsert_documentA
Create or update a document in a CosmosDB container (upsert operation).
If a document with the same id and partition key exists, it will be replaced. If it doesn't exist, a new document will be created.
Example: mcp_upsert_document({ container_id: 'users', document: {id: 'user-456', email: 'test@example.com', lastUpdated: '2024-01-15'}, partition_key: 'user-456', connection_id: 'athlete' })
Inputs: container_id (required), document (required), partition_key (required), connection_id.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 13 tools
Every tool has a clearly distinct purpose, from schema analysis to CRUD operations to listing resources. Even the two query tools (mcp_get_documents and mcp_cosmos_query) are well-differentiated by complexity, with descriptions guiding appropriate use.
All tools follow a consistent mcp_verb_noun pattern with snake_case, making it easy to predict tool names. The naming convention is uniform across all 13 tools, with no mixing of styles.
With 13 tools, the set is well-scoped for a CosmosDB service. It covers all essential operations (CRUD, schema analysis, container info, list resources) without unnecessary bloat or gaps.
The tool surface covers the core CRUD lifecycle, schema analysis, container configuration, and statistics. Minor gaps like batch operations or container creation/deletion are absent but acceptable for a typical usage scope.
Related MCP Connectors
A Model Context Protocol server for Wix AI tools
Model Context Protocol server for Studex tools, notifications, and profile integrations
A comprehensive Model Context Protocol (MCP) server that enables AI assistants to interact with yo…
Model Context Protocol server for todo.vu task management and time tracking.
Related MCP Servers
- AlicenseAqualityDmaintenanceThis server implements the Model Context Protocol for seamless interaction with Azure Blob Storage and Cosmos DB, enabling automatic logging and audit tracking of operations.195MIT
- AlicenseNot gradedqualityDmaintenanceA Model Context Protocol server that provides file system operations, analysis, and manipulation capabilities through a standardized tool interface.6MIT
- AlicenseBqualityDmaintenanceA comprehensive Model Context Protocol server for SQL Server database operations that provides 10 powerful tools for database analysis, object discovery, and data manipulation.11797 npm15MIT
- AlicenseNot gradedqualityDmaintenanceA Model Context Protocol server for interacting with MSSQL and PostgreSQL databases, offering tools for schema exploration and SQL execution. It features configurable query modes for safety and supports advanced authentication methods like Windows Auth and SSL.8 npmMIT