Skip to main content
Glama
CaptainCrouton89

MCP Server Boilerplate

mongo-count-documents

Count documents in a MongoDB collection using a query filter to get precise document totals for data analysis and monitoring.

Instructions

Count documents in a MongoDB collection

Input Schema

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

Implementation Reference

  • The main handler function for the 'mongo-count-documents' tool. It ensures a connection to the specified MongoDB database, retrieves the collection, counts the documents matching the optional filter using countDocuments(), and returns a text response with the count.
    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 input schema defining parameters: database (string), collection (string), and optional filter (JSON 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 using server.tool(), including name, description, schema, and 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'}`);
        }
      }
    );
  • Helper function to ensure MongoDB client connection and database instance are available, used by the tool handler.
    async function ensureConnection(dbName: string): Promise<Db> {
      if (!mongoClient) {
        const uri = getMongoUri();
        mongoClient = new MongoClient(uri);
        await mongoClient.connect();
      }
      
      if (!databases.has(dbName)) {
        databases.set(dbName, mongoClient.db(dbName));
      }
      
      return databases.get(dbName)!;
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure but provides minimal information. It doesn't mention performance characteristics (e.g., whether this uses MongoDB's countDocuments method vs estimatedDocumentCount), whether it requires specific permissions, or what happens with large collections. The description states what the tool does but not how it behaves.

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 perfectly concise at just 6 words - every word earns its place. It's front-loaded with the core functionality and wastes no space on unnecessary elaboration. This is an excellent example of efficient communication.

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

Completeness2/5

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

For a database query tool with 3 parameters (including a complex filter object) and no annotations or output schema, the description is insufficient. It doesn't explain what the tool returns (just a number? metadata?), how errors are handled, or provide any context about the filter parameter's capabilities beyond what's in the schema. The description should do more to compensate for the lack of structured metadata.

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?

The description mentions 'documents in a MongoDB collection' which implies the need for database and collection parameters, but adds no semantic value beyond what the 100% schema coverage already provides. The schema already documents all three parameters clearly, so the description doesn't enhance understanding of what each parameter means or how they interact.

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 could also provide count information through different mechanisms.

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 could count by returning array length) and 'mongo-aggregate' (which could include count operations), there's no indication of when this specialized count tool is preferred or what its performance characteristics might be.

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

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