Skip to main content
Glama
TrueOleg

MCP Mac Apps Server

by TrueOleg

mongodb_find_documents

Search and retrieve documents from MongoDB collections using filters and limits to find specific data.

Instructions

Находит документы в коллекции

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
databaseNameYesИмя базы данных
collectionNameYesИмя коллекции
filterNoJSON строка с фильтром для поиска (необязательно)
limitNoМаксимальное количество документов (по умолчанию 100)

Implementation Reference

  • The primary handler function for the 'mongodb_find_documents' tool. Connects to MongoDB, parses optional filter JSON, queries the specified collection with limit, converts ObjectIds to strings, and returns formatted results as MCP content.
    private async mongodbFindDocuments(
      databaseName: string,
      collectionName: string,
      filterJson?: string,
      limit: number = 100
    ) {
      const client = await this.getMongoClient();
      try {
        const db = client.db(databaseName);
        const collection = db.collection(collectionName);
        const filter = filterJson ? JSON.parse(filterJson) : {};
        const documents = await collection
          .find(filter)
          .limit(limit)
          .toArray();
        
        // Преобразуем ObjectId в строки для JSON
        const documentsStr = JSON.stringify(
          documents.map((doc) => ({
            ...doc,
            _id: doc._id.toString(),
          })),
          null,
          2
        );
        
        return {
          content: [
            {
              type: "text",
              text: `Найдено документов: ${documents.length}\n\n${documentsStr}`,
            },
          ],
        };
      } catch (error) {
        throw new Error(
          `Ошибка поиска документов: ${error instanceof Error ? error.message : String(error)}`
        );
      } finally {
        await client.close();
      }
    }
  • Input schema definition for the 'mongodb_find_documents' tool, registered in the listTools response.
    name: "mongodb_find_documents",
    description: "Находит документы в коллекции",
    inputSchema: {
      type: "object",
      properties: {
        databaseName: {
          type: "string",
          description: "Имя базы данных",
        },
        collectionName: {
          type: "string",
          description: "Имя коллекции",
        },
        filter: {
          type: "string",
          description: "JSON строка с фильтром для поиска (необязательно)",
        },
        limit: {
          type: "number",
          description: "Максимальное количество документов (по умолчанию 100)",
        },
      },
      required: ["databaseName", "collectionName"],
    },
  • src/index.ts:366-372 (registration)
    Registration/dispatch of the 'mongodb_find_documents' handler in the CallToolRequest switch statement.
    case "mongodb_find_documents":
      return await this.mongodbFindDocuments(
        args?.databaseName as string,
        args?.collectionName as string,
        args?.filter as string | undefined,
        args?.limit as number | undefined
      );
  • Handler function for 'mongodb_find_documents' in the Python version of the server (note: dispatch is commented out, so not active). Similar logic to TS version.
    def mongodb_find_documents(
        database_name: str,
        collection_name: str,
        filter_json: Optional[str] = None,
        limit: int = 100,
    ) -> str:
        """Finds documents in collection"""
        client = MongoClient(MONGODB_URI)
        try:
            db = client[database_name]
            collection = db[collection_name]
            filter_dict = json.loads(filter_json) if filter_json else {}
            documents = list(collection.find(filter_dict).limit(limit))
            # Convert ObjectId to strings
            for doc in documents:
                if "_id" in doc:
                    doc["_id"] = str(doc["_id"])
            documents_str = json.dumps(documents, ensure_ascii=False, indent=2)
            return f"Found documents: {len(documents)}\n\n{documents_str}"
        except Exception as e:
            raise Exception(f"Error finding documents: {str(e)}")
        finally:
            client.close()
  • Input schema for 'mongodb_find_documents' in the Python server's tool list.
    "name": "mongodb_find_documents",
    "description": "Finds documents in collection",
    "inputSchema": {
        "type": "object",
        "properties": {
            "databaseName": {
                "type": "string",
                "description": "Database name",
            },
            "collectionName": {
                "type": "string",
                "description": "Collection name",
            },
            "filter": {
                "type": "string",
                "description": "JSON string with search filter (optional)",
            },
            "limit": {
                "type": "number",
                "description": "Maximum number of documents (default 100)",
            },
        },
        "required": ["databaseName", "collectionName"],
    },
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. The description only states it 'finds documents', implying a read operation, but doesn't disclose any behavioral traits like whether it's safe (non-destructive), what permissions are required, how results are returned (e.g., format, pagination), or any rate limits. This leaves significant gaps for an agent to understand how to use it effectively.

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

Conciseness4/5

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

The description is a single, efficient sentence in Russian ('Находит документы в коллекции'), which is appropriately concise and front-loaded. There's no wasted text, making it easy to parse, though it could benefit from more detail to improve clarity and completeness.

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 MongoDB find operation with 4 parameters, no annotations, and no output schema, the description is incomplete. It doesn't explain what the tool returns (e.g., document format, error handling) or provide usage context. This leaves the agent with insufficient information to invoke the tool correctly, especially without annotations to cover behavioral aspects.

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 input schema has 100% description coverage, with clear parameter descriptions in Russian (e.g., 'Имя базы данных' for databaseName). The tool description adds no additional meaning beyond what the schema provides, such as explaining filter syntax or limit defaults in more detail. With high schema coverage, the baseline score of 3 is appropriate, as the schema adequately documents parameters without extra help from the description.

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

Purpose2/5

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

The description 'Находит документы в коллекции' (Finds documents in a collection) is a tautology that essentially restates the tool name 'mongodb_find_documents'. It doesn't specify what type of documents or provide any distinguishing details from sibling tools like mongodb_list_collections or mongodb_delete_document. The purpose is vague and lacks specificity about the MongoDB context.

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

Usage Guidelines1/5

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

No guidance is provided on when to use this tool versus alternatives. It doesn't mention sibling tools like mongodb_list_collections for listing collections without filtering or mongodb_delete_document for deleting documents. There's no context about prerequisites, such as needing an existing database and collection, or when to use filter vs. limit parameters.

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/TrueOleg/MCP-expirements'

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