Skip to main content
Glama
jonfreeland

MongoDB MCP Server

by jonfreeland

text_search

Search MongoDB collections using full-text queries with stemming, stop word removal, and relevance scoring to find specific documents based on text content.

Instructions

Perform a full-text search on a collection.

Requirements:

  • Collection must have a text index

  • Only one text index per collection is allowed

Features:

  • Supports phrases and keywords

  • Word stemming

  • Stop words removal

  • Text score ranking

Example: use_mcp_tool with server_name: "mongodb", tool_name: "text_search", arguments: { "collection": "articles", "searchText": "mongodb database", "filter": { "published": true }, "limit": 10, "includeScore": true }

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
databaseNoDatabase name (optional if default database is configured)
collectionYesCollection name
searchTextYesText to search for
filterNoAdditional MongoDB query filter (optional)
limitNoMaximum number of results to return (optional)
includeScoreNoInclude text search score in results (optional)

Implementation Reference

  • Handler function for executing the text_search tool. Performs full-text search using MongoDB's $text operator, supports additional filters, scoring, sorting by score, and limits. Includes error handling for missing text indexes.
    case 'text_search': {
      const { database, collection, searchText, filter, limit, includeScore } = request.params
        .arguments as {
        database?: string;
        collection: string;
        searchText: string;
        filter?: object;
        limit?: number;
        includeScore?: boolean;
      };
      const dbName = database || this.defaultDatabase;
      if (!dbName) {
        throw new McpError(
          ErrorCode.InvalidRequest,
          'Database name is required when no default database is configured'
        );
      }
    
      const db = client.db(dbName);
      
      try {
        const searchQuery = {
          $text: { $search: searchText },
          ...(filter || {}),
        };
    
        const projection = includeScore ? { score: { $meta: 'textScore' } } : undefined;
        let query = db.collection(collection).find(searchQuery);
    
        if (projection) {
          query = query.project(projection);
        }
        if (includeScore) {
          query = query.sort({ score: { $meta: 'textScore' } });
        }
        if (limit) {
          query = query.limit(limit);
        }
    
        const results = await query.toArray();
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(results, null, 2),
            },
          ],
        };
      } catch (error) {
        // Check if error is due to missing text index
        if (error instanceof Error && error.message.includes('text index')) {
          throw new McpError(
            ErrorCode.InvalidRequest,
            'No text index found on this collection. Create a text index first using db.collection.createIndex({ "field": "text" })'
          );
        }
        throw error;
      }
    }
  • Input schema definition for the text_search tool, specifying parameters like searchText, collection, optional filter, limit, and includeScore.
    inputSchema: {
      type: 'object',
      properties: {
        database: {
          type: 'string',
          description: 'Database name (optional if default database is configured)',
        },
        collection: {
          type: 'string',
          description: 'Collection name',
        },
        searchText: {
          type: 'string',
          description: 'Text to search for',
        },
        filter: {
          type: 'object',
          description: 'Additional MongoDB query filter (optional)',
        },
        limit: {
          type: 'number',
          description: 'Maximum number of results to return (optional)',
          minimum: 1,
          maximum: 1000,
        },
        includeScore: {
          type: 'boolean',
          description: 'Include text search score in results (optional)',
        },
      },
      required: ['collection', 'searchText'],
    },
  • src/index.ts:946-1002 (registration)
    Registration of the text_search tool in the ListTools response, including name, description, and input schema.
              name: 'text_search',
              description: `Perform a full-text search on a collection.
    
    Requirements:
    - Collection must have a text index
    - Only one text index per collection is allowed
    
    Features:
    - Supports phrases and keywords
    - Word stemming
    - Stop words removal
    - Text score ranking
    
    Example:
    use_mcp_tool with
      server_name: "mongodb",
      tool_name: "text_search",
      arguments: {
        "collection": "articles",
        "searchText": "mongodb database",
        "filter": { "published": true },
        "limit": 10,
        "includeScore": true
      }`,
              inputSchema: {
                type: 'object',
                properties: {
                  database: {
                    type: 'string',
                    description: 'Database name (optional if default database is configured)',
                  },
                  collection: {
                    type: 'string',
                    description: 'Collection name',
                  },
                  searchText: {
                    type: 'string',
                    description: 'Text to search for',
                  },
                  filter: {
                    type: 'object',
                    description: 'Additional MongoDB query filter (optional)',
                  },
                  limit: {
                    type: 'number',
                    description: 'Maximum number of results to return (optional)',
                    minimum: 1,
                    maximum: 1000,
                  },
                  includeScore: {
                    type: 'boolean',
                    description: 'Include text search score in results (optional)',
                  },
                },
                required: ['collection', 'searchText'],
              },
            },
Behavior3/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 adds useful context beyond basic functionality: it lists features (e.g., word stemming, stop words removal) and requirements (e.g., text index needed), which helps the agent understand operational constraints. However, it doesn't cover aspects like error handling, performance implications, or authentication needs, leaving gaps for a tool with complex behavior.

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 well-structured with sections (Requirements, Features, Example) and front-loaded with the core purpose. It's appropriately sized, but the example is lengthy and could be more concise. Most sentences earn their place by adding value, though some redundancy exists (e.g., repeating parameter names in the example).

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 complexity (6 parameters, no output schema, no annotations), the description is moderately complete. It covers purpose, requirements, and features, but lacks details on output format, error cases, or integration with sibling tools. Without an output schema, the agent might struggle to interpret results, making this description adequate but with clear gaps for effective use.

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 6 parameters thoroughly. The description doesn't add significant meaning beyond the schema—it mentions 'searchText' and 'filter' in the example but without extra semantics. The baseline score of 3 is appropriate as the schema does the heavy lifting, though the description could have elaborated on parameter interactions.

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 tool's purpose: 'Perform a full-text search on a collection.' It specifies the verb ('full-text search') and resource ('collection'), making the function unambiguous. However, it doesn't explicitly differentiate from sibling tools like 'query' or 'geo_query' that might also search collections but with different methods.

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

Usage Guidelines3/5

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

The description provides some usage context through 'Requirements' (e.g., collection must have a text index, only one text index allowed), which implies when this tool is applicable versus alternatives. However, it doesn't explicitly state when to use this tool over sibling tools like 'query' for non-text searches or 'geo_query' for spatial queries, leaving some ambiguity.

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/jonfreeland/mongodb-mcp'

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