Skip to main content
Glama
hendrickcastro

MCP CosmosDB

mcp_get_documents

Get documents from a CosmosDB container with simple equality filters and ordering by timestamp. Use partition key for faster queries and order_by to find newest or oldest records.

Instructions

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'}})

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
container_idYesThe ID/name of the container to query
limitNoMaximum number of documents to return (default: 100)
partition_keyNoOptional partition key value to filter by. Improves performance significantly.
filter_conditionsNoSimple equality filters as key-value pairs. Example: {status: 'active', type: 'premium'}
order_byNoField name to order results by. Use '_ts' for timestamp ordering (most recent/oldest). Example: '_ts', 'creationDate', 'name'
order_directionNoSort direction: 'ASC' for ascending (oldest first), 'DESC' for descending (newest first). Default: 'ASC'ASC
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 actual handler function for mcp_get_documents. It queries a CosmosDB container with optional filters (equality), ordering, partition key, and limit. Builds a SQL query dynamically, executes it via the container's items.query, and returns the documents.
    export const mcp_get_documents = async (args: { 
      container_id: string; 
      limit?: number;
      partition_key?: PartitionKeyValue;
      filter_conditions?: Record<string, any>;
      order_by?: string;
      order_direction?: 'ASC' | 'DESC';
      connection_id?: string;
    }): Promise<ToolResult<DocumentInfo[]>> => {
      const { container_id, limit = 100, partition_key, filter_conditions, order_by, order_direction = 'ASC', connection_id } = args;
      log(`Executing mcp_get_documents with: ${JSON.stringify(args)}`);
    
      try {
        const container = getContainer(container_id, connection_id);
    
        // Build query with proper TOP clause (not subquery)
        const whereClauses: string[] = [];
        const parameters: Array<{ name: string; value: any }> = [];
    
        // Add filter conditions
        if (filter_conditions && Object.keys(filter_conditions).length > 0) {
          Object.entries(filter_conditions).forEach(([key, value], index) => {
            const paramName = `@param${index}`;
            parameters.push({ name: paramName, value });
            whereClauses.push(`c.${key} = ${paramName}`);
          });
        }
    
        // Build final query
        let query = `SELECT * FROM c`;
        if (whereClauses.length > 0) {
          query += ` WHERE ${whereClauses.join(' AND ')}`;
        }
        
        // Add ORDER BY clause if specified
        if (order_by) {
          const direction = order_direction === 'DESC' ? 'DESC' : 'ASC';
          query += ` ORDER BY c.${order_by} ${direction}`;
        }
    
        const querySpec = { query, parameters };
    
        // Query options
        const options: any = { maxItemCount: limit };
        if (partition_key !== undefined) {
          options.partitionKey = partition_key;
        }
    
        const { resources: documents } = await container.items.query(querySpec, options).fetchAll();
        
        // Apply limit after query (since ORDER BY with TOP can be problematic in CosmosDB)
        const limitedDocuments = documents.slice(0, limit);
    
        return { success: true, data: limitedDocuments };
      } catch (error: any) {
        log(`Error in mcp_get_documents for container ${container_id}: ${error.message}`);
        return { success: false, error: error.message };
      }
    };
  • The input parameter schema for the handler function - accepts container_id (required), limit, partition_key, filter_conditions, order_by, order_direction, and connection_id.
    export const mcp_get_documents = async (args: { 
      container_id: string; 
      limit?: number;
      partition_key?: PartitionKeyValue;
      filter_conditions?: Record<string, any>;
      order_by?: string;
      order_direction?: 'ASC' | 'DESC';
      connection_id?: string;
    }): Promise<ToolResult<DocumentInfo[]>> => {
  • The MCP tool registration schema for mcp_get_documents, defining the inputSchema with container_id, limit, partition_key, filter_conditions, order_by, order_direction, and connection_id properties.
      // 6. Get Documents - Simple filtering without SQL
      {
        name: "mcp_get_documents",
        description: `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'}})`,
        inputSchema: {
          type: "object",
          properties: {
            container_id: {
              type: "string",
              description: "The ID/name of the container to query"
            },
            limit: {
              type: "number",
              description: "Maximum number of documents to return (default: 100)",
              default: 100
            },
            partition_key: {
              type: ["string", "number", "boolean"],
              description: "Optional partition key value to filter by. Improves performance significantly."
            },
            filter_conditions: {
              type: "object",
              description: "Simple equality filters as key-value pairs. Example: {status: 'active', type: 'premium'}"
            },
            order_by: {
              type: "string",
              description: "Field name to order results by. Use '_ts' for timestamp ordering (most recent/oldest). Example: '_ts', 'creationDate', 'name'"
            },
            order_direction: {
              type: "string",
              enum: ["ASC", "DESC"],
              description: "Sort direction: 'ASC' for ascending (oldest first), 'DESC' for descending (newest first). Default: 'ASC'",
              default: "ASC"
            },
            ...connectionIdProperty
          },
          required: ["container_id"]
        }
      },
  • src/tools.ts:139-185 (registration)
    The tool is registered in the MCP_COSMOSDB_TOOLS array with name 'mcp_get_documents' and its description/input schema.
        name: "mcp_get_documents",
        description: `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'}})`,
        inputSchema: {
          type: "object",
          properties: {
            container_id: {
              type: "string",
              description: "The ID/name of the container to query"
            },
            limit: {
              type: "number",
              description: "Maximum number of documents to return (default: 100)",
              default: 100
            },
            partition_key: {
              type: ["string", "number", "boolean"],
              description: "Optional partition key value to filter by. Improves performance significantly."
            },
            filter_conditions: {
              type: "object",
              description: "Simple equality filters as key-value pairs. Example: {status: 'active', type: 'premium'}"
            },
            order_by: {
              type: "string",
              description: "Field name to order results by. Use '_ts' for timestamp ordering (most recent/oldest). Example: '_ts', 'creationDate', 'name'"
            },
            order_direction: {
              type: "string",
              enum: ["ASC", "DESC"],
              description: "Sort direction: 'ASC' for ascending (oldest first), 'DESC' for descending (newest first). Default: 'ASC'",
              default: "ASC"
            },
            ...connectionIdProperty
          },
          required: ["container_id"]
        }
      },
  • src/server.ts:138-139 (registration)
    The CallTool handler routes the 'mcp_get_documents' case to toolHandlers.mcp_get_documents (imported from './mcp-server.js' which re-exports from tools/index.ts which re-exports from tools/dataOperations.ts).
    case 'mcp_get_documents':
        result = await toolHandlers.mcp_get_documents(input as any);
Behavior3/5

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

No annotations are provided, so the description carries full burden. It implies a read operation but does not explicitly state side effects, idempotency, or cost implications. However, it does not mislead and accurately describes the tool's capabilities.

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

Conciseness5/5

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

The description is well-structured: a brief purpose statement, followed by a bulleted list of when to use, then two illustrative examples. No redundant sentences, and every sentence adds value.

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?

With 7 parameters and no output schema, the description covers the tool's use cases well, including examples for key scenarios. However, it omits mention of return format or pagination, which could be helpful for completeness.

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 coverage is 100%, so the description adds value by providing concrete examples, explaining '_ts' for timestamp ordering, and showing filter_conditions usage. It goes beyond schema by contextualizing parameters in real queries.

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?

Clearly states it gets documents with simple filters/ordering, and explicitly contrasts with mcp_cosmos_query for complex SQL queries. The verb 'get' and resource 'documents' are precise, and examples reinforce the purpose.

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

Usage Guidelines5/5

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

Explicitly tells when to use (simple queries, equality filters, partition key filtering, ordering) and when not to (complex queries, directing to mcp_cosmos_query). Provides best-use scenarios in a bulleted list.

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