Skip to main content
Glama
hendrickcastro

MCP CosmosDB

mcp_container_stats

Analyze container statistics including document count and partition key distribution to monitor data distribution and optimize performance in CosmosDB.

Instructions

Get statistical information about a container including document count and partition key distribution

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
container_idYesThe ID of the container to analyze
sample_sizeNoSample size for statistics calculation

Implementation Reference

  • The primary handler function for the mcp_container_stats tool. It queries the CosmosDB container for document count, samples documents to estimate size and partition key distribution, and returns ContainerStats.
    export const mcp_container_stats = async (args: { container_id: string; sample_size?: number }): Promise<ToolResult<ContainerStats>> => {
      const { container_id, sample_size = 1000 } = args;
      console.log('Executing mcp_container_stats with:', args);
    
      try {
        const container = getContainer(container_id);
        
        // Query to count total documents
        const countQuery = 'SELECT VALUE COUNT(1) FROM c';
        const { resources: countResult } = await container.items.query(countQuery).fetchAll();
        const documentCount = countResult[0] || 0;
    
        // Get partition key path for statistics
        const { resource: containerDef } = await container.read();
        if (!containerDef || !containerDef.partitionKey || !containerDef.partitionKey.paths || containerDef.partitionKey.paths.length === 0) {
          throw new Error(`Container ${container_id} does not have a valid partition key defined`);
        }
        const partitionKeyPath = containerDef.partitionKey.paths[0];
    
        // Sample documents to estimate size and analyze partitions
        const sampleQuery = `SELECT TOP ${sample_size} * FROM c`;
        const { resources: sampleDocs } = await container.items.query(sampleQuery).fetchAll();
    
        // Calculate estimated size based on sample
        let totalSampleSize = 0;
        const partitionStats: Record<string, { count: number; size: number }> = {};
    
        sampleDocs.forEach(doc => {
          const docSize = JSON.stringify(doc).length;
          totalSampleSize += docSize;
    
          // Get partition key value
          const partitionValue = getNestedProperty(doc, partitionKeyPath.substring(1)); // Remove leading '/'
          const partitionKey = String(partitionValue || 'undefined');
    
          if (!partitionStats[partitionKey]) {
            partitionStats[partitionKey] = { count: 0, size: 0 };
          }
          partitionStats[partitionKey].count++;
          partitionStats[partitionKey].size += docSize;
        });
    
        // Estimate total size
        const avgDocSize = sampleDocs.length > 0 ? totalSampleSize / sampleDocs.length : 0;
        const estimatedSizeInKB = Math.round((documentCount * avgDocSize) / 1024);
    
        // Convert partition stats
        const partitionKeyStatistics = Object.entries(partitionStats).map(([key, stats]) => ({
          partitionKeyValue: key,
          documentCount: Math.round((stats.count / sampleDocs.length) * documentCount),
          sizeInKB: Math.round(stats.size / 1024)
        }));
    
        const containerStats: ContainerStats = {
          documentCount,
          sizeInKB: estimatedSizeInKB,
          partitionKeyStatistics
        };
    
        return { success: true, data: containerStats };
      } catch (error: any) {
        console.error(`Error in mcp_container_stats for container ${container_id}: ${error.message}`);
        return { success: false, error: error.message };
      }
    };
  • The input schema definition for the mcp_container_stats tool as part of the MCP_COSMOSDB_TOOLS array, used for tool listing and validation.
    {
      name: "mcp_container_stats",
      description: "Get statistical information about a container including document count and partition key distribution",
      inputSchema: {
        type: "object",
        properties: {
          container_id: {
            type: "string",
            description: "The ID of the container to analyze"
          },
          sample_size: {
            type: "number",
            description: "Sample size for statistics calculation",
            default: 1000
          }
        },
        required: ["container_id"]
      }
    },
  • src/server.ts:100-102 (registration)
    Dispatch/registration in the CallTool handler switch statement that routes execution to the mcp_container_stats handler.
    case 'mcp_container_stats':
        result = await toolHandlers.mcp_container_stats(input as any);
        break;
  • Helper function used within mcp_container_stats to extract partition key values from nested document properties.
    function getNestedProperty(obj: any, path: string): any {
      return path.split('/').reduce((current, key) => {
        return current && current[key] !== undefined ? current[key] : undefined;
      }, obj);
    } 
  • src/tools/index.ts:8-8 (registration)
    Re-export of the mcp_container_stats handler from containerAnalysis.ts, making it available via tools/index.ts which is imported by mcp-server.ts.
    mcp_container_stats
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions what information is retrieved but doesn't cover aspects like whether this is a read-only operation, performance impact, rate limits, or error conditions. For a tool with statistical analysis, more context on behavior (e.g., sampling effects) would be helpful.

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 a single, efficient sentence that front-loads the purpose with zero waste. Every word earns its place by specifying the action, resource, and key outputs without redundancy.

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

Completeness3/5

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

Given no annotations and no output schema, the description is minimally complete for a read operation but lacks depth. It covers what the tool does but misses behavioral details and output expectations. For a statistical tool with parameters, more context on results and usage would improve completeness.

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

Parameters3/5

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

Schema description coverage is 100%, so the schema already documents both parameters (container_id and sample_size) well. The description adds no additional parameter semantics beyond implying statistical analysis, which aligns with the schema but doesn't provide extra value like usage tips or constraints.

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

Purpose4/5

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

The description clearly states the verb 'Get' and the resource 'statistical information about a container', specifying what information is retrieved (document count and partition key distribution). It distinguishes from siblings like mcp_container_info (likely general info) and mcp_list_containers (listing containers), but doesn't explicitly differentiate them.

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

Usage Guidelines2/5

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

No guidance on when to use this tool versus alternatives like mcp_container_info or mcp_analyze_schema is provided. The description implies usage for statistical analysis but lacks context on prerequisites, exclusions, or specific scenarios where this tool is preferred.

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