Skip to main content
Glama
CaptainCrouton89

MCP Server Boilerplate

mongo-find-documents

Query documents from a MongoDB collection using database name, collection name, and optional filters to retrieve specific data records.

Instructions

Query documents from a MongoDB collection

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
databaseYesDatabase name
collectionYesCollection name
filterNoQuery filter as JSON object (optional)
limitNoMaximum number of documents to return (optional)

Implementation Reference

  • The handler function that executes the mongo-find-documents tool: connects to MongoDB database, finds documents using the provided filter and optional limit, formats the output as truncated JSON, and returns it in the MCP response format.
    async ({ database: dbName, collection: collectionName, filter = {}, limit }) => {
      try {
        const db = await ensureConnection(dbName);
        const collection: Collection = db.collection(collectionName);
        
        let cursor = collection.find(filter);
        if (limit) {
          cursor = cursor.limit(limit);
        }
        
        const documents = await cursor.toArray();
        
        const formattedOutput = formatJsonOutput(documents);
        
        return {
          content: [
            {
              type: "text",
              text: `Found ${documents.length} document(s):\n\n${formattedOutput}`,
            },
          ],
        };
      } catch (error) {
        throw new Error(`Failed to find documents: ${error instanceof Error ? error.message : 'Unknown error'}`);
      }
    }
  • Zod schema for the tool's input parameters: required database and collection names, optional filter object and limit number.
    {
      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)"),
      limit: z.number().optional().describe("Maximum number of documents to return (optional)"),
    },
  • src/index.ts:131-166 (registration)
    Registration of the "mongo-find-documents" tool with the MCP server, specifying name, description, input schema, and inline handler function.
    server.tool(
      "mongo-find-documents",
      "Query documents from 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)"),
        limit: z.number().optional().describe("Maximum number of documents to return (optional)"),
      },
      async ({ database: dbName, collection: collectionName, filter = {}, limit }) => {
        try {
          const db = await ensureConnection(dbName);
          const collection: Collection = db.collection(collectionName);
          
          let cursor = collection.find(filter);
          if (limit) {
            cursor = cursor.limit(limit);
          }
          
          const documents = await cursor.toArray();
          
          const formattedOutput = formatJsonOutput(documents);
          
          return {
            content: [
              {
                type: "text",
                text: `Found ${documents.length} document(s):\n\n${formattedOutput}`,
              },
            ],
          };
        } catch (error) {
          throw new Error(`Failed to find documents: ${error instanceof Error ? error.message : 'Unknown error'}`);
        }
      }
    );
  • Helper function to ensure a MongoDB connection and database instance is 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)!;
    }
  • Helper function to format and clean up truncated JSON output for the tool response, called by the handler.
    function formatJsonOutput(data: unknown): string {
      const truncatedData = truncateForOutput(data);
      let outputText = JSON.stringify(truncatedData, null, 2);
      
      outputText = outputText.replace(
        /"\.\.\.(\d+) more items"/g,
        "...$1 more items"
      );
      outputText = outputText.replace(
        /"\.\.\.(\d+) more properties": "\.\.\.?"/g,
        "...$1 more properties"
      );
      
      return outputText;
    }
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. It states the action ('Query') but doesn't cover critical aspects like read-only nature (implied but not explicit), potential performance impacts, error handling, or return format. This is inadequate for a tool with database operations.

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 with zero waste. It's front-loaded and appropriately sized for the tool's complexity, making it easy to parse without unnecessary elaboration.

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?

Given the complexity of a database query tool with no annotations and no output schema, the description is insufficient. It lacks details on behavioral traits (e.g., read-only, error cases), return values, or how it differs from siblings, leaving significant gaps for an AI agent to operate effectively.

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 input schema fully documents all parameters (database, collection, filter, limit). The description adds no additional meaning beyond what the schema provides, such as examples or usage tips for the filter parameter. Baseline 3 is appropriate when the schema handles parameter documentation.

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 'Query documents from a MongoDB collection' clearly states the verb ('Query') and resource ('documents from a MongoDB collection'), making the purpose understandable. However, it doesn't explicitly differentiate from sibling tools like mongo-aggregate or mongo-count-documents, which also involve querying operations, so it misses full sibling distinction.

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-aggregate for complex queries and mongo-count-documents for counting, there's no mention of context, prerequisites, or exclusions, leaving the agent to guess based on tool names alone.

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