Skip to main content
Glama
ricleedo

MCP Server Boilerplate

by ricleedo

mongo-count-documents

Count documents in a MongoDB collection using a query filter to retrieve specific data counts from your database.

Instructions

Count documents in a MongoDB collection

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
databaseYesDatabase name
collectionYesCollection name
filterNoQuery filter as JSON object (optional)

Implementation Reference

  • Handler function that ensures database connection, retrieves the collection, counts documents matching the optional filter using countDocuments, and returns the count in a text response.
    async ({ database: dbName, collection: collectionName, filter = {} }) => {
      try {
        const db = await ensureConnection(dbName);
        const collection: Collection = db.collection(collectionName);
        
        const count = await collection.countDocuments(filter);
        
        return {
          content: [
            {
              type: "text",
              text: `Found ${count} document(s) matching the filter`,
            },
          ],
        };
      } catch (error) {
        throw new Error(`Failed to count documents: ${error instanceof Error ? error.message : 'Unknown error'}`);
      }
    }
  • Zod schema defining input parameters: database name, collection name, and optional filter object.
    {
      database: z.string().describe("Database name"),
      collection: z.string().describe("Collection name"),
      filter: z.record(z.any()).optional().describe("Query filter as JSON object (optional)"),
    },
  • src/index.ts:264-291 (registration)
    Registration of the 'mongo-count-documents' tool with the MCP server, including description, input schema, and inline handler function.
    server.tool(
      "mongo-count-documents",
      "Count documents in a MongoDB collection",
      {
        database: z.string().describe("Database name"),
        collection: z.string().describe("Collection name"),
        filter: z.record(z.any()).optional().describe("Query filter as JSON object (optional)"),
      },
      async ({ database: dbName, collection: collectionName, filter = {} }) => {
        try {
          const db = await ensureConnection(dbName);
          const collection: Collection = db.collection(collectionName);
          
          const count = await collection.countDocuments(filter);
          
          return {
            content: [
              {
                type: "text",
                text: `Found ${count} document(s) matching the filter`,
              },
            ],
          };
        } catch (error) {
          throw new Error(`Failed to count documents: ${error instanceof Error ? error.message : 'Unknown error'}`);
        }
      }
    );
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. While it states the action ('Count documents'), it doesn't mention performance characteristics (e.g., speed on large collections), permission requirements, whether it's a read-only operation, or what happens with malformed filters. This leaves significant gaps for an agent to understand the tool's behavior.

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, clear sentence that directly states the tool's purpose without any unnecessary words. It's perfectly front-loaded and wastes no space, making it highly efficient for an agent to parse.

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 the tool's moderate complexity (counting with optional filtering), no annotations, and no output schema, the description is minimally adequate. It identifies the core function but lacks details on behavior, usage context, or return format. For a tool with three parameters and no structured safety hints, more completeness would be beneficial.

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 all three parameters (database, collection, filter) with their types and optionality. The description adds no additional parameter information beyond what's in the schema, so it meets the baseline but doesn't provide extra value like explaining filter syntax or examples.

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 ('Count') and resource ('documents in a MongoDB collection'), making the purpose immediately understandable. However, it doesn't differentiate from sibling tools like 'mongo-find-documents' or 'mongo-aggregate' which might also provide counting capabilities, so it doesn't reach the highest score.

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?

The description provides no guidance on when to use this tool versus alternatives. With siblings like 'mongo-find-documents' (which might return counts) and 'mongo-aggregate' (which can perform complex counting operations), there's no indication of when this specific count tool is preferred or what its limitations are.

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/ricleedo/mongo-boilerplate-mcp'

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