Skip to main content
Glama
hendrickcastro

MCP CosmosDB

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

TableJSON Schema
NameRequiredDescriptionDefault
container_idYesThe ID/name of the container to query
queryYesCosmosDB 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'
parametersNoQuery parameters as key-value pairs (without @ prefix). Example: {status: 'active', limit: 10}
max_itemsNoMaximum number of items to return (default: 100, max recommended: 1000)
enable_cross_partitionNoEnable cross-partition queries. Set to true unless querying within a single partition key value.
connection_idNoID of the connection to use. Use mcp_list_connections to see available connections. If not specified, uses the default connection.

Implementation Reference

  • 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 };
      }
    };
  • 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;
  • 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 })) : []
    };
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Discloses important performance implications like timeouts and high RU consumption for SELECT *. No annotations exist, so the description carries the full burden. Could mention pagination or error scenarios, but covers key behaviors.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Well-structured with a concise opening, bolded warnings, and clear examples. Some redundancy in examples but overall efficient for the depth of information provided.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Covers syntax, parameters, warnings, and example queries. Without an output schema, the description provides sufficient context for correct usage, though it could mention result format briefly.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so baseline is 3. The description adds value by providing examples of parameter usage and showing the @paramName syntax, which complements the schema.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states 'Execute a CosmosDB SQL query against a container' and distinguishes itself from sibling tools by specifying it's for 'complex queries with JOINs, aggregations, or custom SQL syntax'.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Provides explicit guidance on when to use (complex queries) and includes strong warnings against SELECT * and recommends TOP N and field projection. However, it does not directly mention alternative tools for simpler operations.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/hendrickcastro/MCPCosmosDB'

If you have feedback or need assistance with the MCP directory API, please join our Discord server