mcp_cosmos_query
Execute complex CosmosDB SQL queries with JOINs, aggregations, and custom syntax. Supports parameterized queries, cross-partition queries, and limits results to avoid high RU consumption.
Instructions
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"}
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| container_id | Yes | The ID/name of the container to query | |
| query | Yes | CosmosDB SQL query. Use 'c' as the alias for the container. ALWAYS use TOP N and specify fields - NEVER use SELECT *. Example: 'SELECT TOP 10 c.id, c.name FROM c WHERE c.active = true' | |
| parameters | No | Query parameters as key-value pairs (without @ prefix). Example: {status: 'active', limit: 10} | |
| max_items | No | Maximum number of items to return (default: 100, max recommended: 1000) | |
| enable_cross_partition | No | Enable cross-partition queries. Set to true unless querying within a single partition key value. | |
| connection_id | No | ID of the connection to use. Use mcp_list_connections to see available connections. If not specified, uses the default connection. |
Implementation Reference
- src/tools/dataOperations.ts:51-91 (handler)The main handler function for mcp_cosmos_query - named mcp_execute_query. It executes a CosmosDB SQL query against a container, supporting parameters, max_items, and cross-partition queries. Returns documents and query stats (requestCharge, executionTimeMs, documentCount).
export const mcp_execute_query = async (args: { container_id: string; query: string; parameters?: Record<string, any>; max_items?: number; enable_cross_partition?: boolean; connection_id?: string; }): Promise<ToolResult<{ documents: any[]; stats: QueryStats }>> => { const { container_id, query, parameters, max_items = 100, enable_cross_partition = true, connection_id } = args; log(`Executing mcp_execute_query with: ${JSON.stringify({ ...args, query: query.substring(0, 100) })}`); try { const container = getContainer(container_id, connection_id); const startTime = Date.now(); // Prepare query spec const querySpec = { query, parameters: parameters ? Object.entries(parameters).map(([name, value]) => ({ name: `@${name}`, value })) : [] }; // Execute query const queryIterator = container.items.query(querySpec, { maxItemCount: max_items }); const { resources: documents, requestCharge } = await queryIterator.fetchAll(); const executionTimeMs = Date.now() - startTime; const stats: QueryStats = { requestCharge, executionTimeMs, documentCount: documents.length }; return { success: true, data: { documents, stats } }; } catch (error: any) { log(`Error in mcp_execute_query for container ${container_id}: ${error.message}`); return { success: false, error: error.message }; } }; - src/tools.ts:86-135 (schema)The input schema definition for mcp_cosmos_query. Defines input properties: container_id (required), query (required), parameters (optional object), max_items (optional number, default 100), enable_cross_partition (optional boolean, default true), and connection_id (optional).
// 5. Query Execution - Advanced SQL queries { name: "mcp_cosmos_query", description: `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"}`, inputSchema: { type: "object", properties: { container_id: { type: "string", description: "The ID/name of the container to query" }, query: { type: "string", description: "CosmosDB SQL query. Use 'c' as the alias for the container. ALWAYS use TOP N and specify fields - NEVER use SELECT *. Example: 'SELECT TOP 10 c.id, c.name FROM c WHERE c.active = true'" }, parameters: { type: "object", description: "Query parameters as key-value pairs (without @ prefix). Example: {status: 'active', limit: 10}" }, max_items: { type: "number", description: "Maximum number of items to return (default: 100, max recommended: 1000)", default: 100 }, enable_cross_partition: { type: "boolean", description: "Enable cross-partition queries. Set to true unless querying within a single partition key value.", default: true }, ...connectionIdProperty }, required: ["container_id", "query"] } }, - src/server.ts:135-137 (registration)Registration of the tool handler in the server's CallToolRequestSchema switch statement. Maps tool name 'mcp_cosmos_query' to the mcp_execute_query handler function.
case 'mcp_cosmos_query': result = await toolHandlers.mcp_execute_query(input as any); break; - src/tools/dataOperations.ts:67-70 (helper)Query parameter preparation logic: Converts the user-provided parameters object (key-value pairs) into CosmosDB parameter format with @ prefix.
const querySpec = { query, parameters: parameters ? Object.entries(parameters).map(([name, value]) => ({ name: `@${name}`, value })) : [] };