Skip to main content
Glama
datastax

Astra DB MCP Server

Official

FindRecord

Search and retrieve records from a specified collection by field value using the Astra DB MCP Server. Define the collection, field, and value to filter results efficiently.

Instructions

Find records in a collection by field value

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
collectionNameYesName of the collection to search in
fieldYesField name to search by (e.g., 'title', '_id', or any property)
limitNoMaximum number of records to return
valueYesValue to search for in the specified field

Implementation Reference

  • Core implementation of the FindRecord tool. Performs exact match search on specified field in a collection, with special handling for _id, fallback to regex partial match if no results, and sanitizes output.
    export async function FindRecord(params: {
      collectionName: string;
      field: string;
      value: string;
      limit?: number;
    }) {
      const { collectionName, field, value, limit = 10 } = params;
    
      const collection = db.collection(collectionName);
    
      // Handle special case for _id field
      if (field === "_id" || field === "id") {
        try {
          // Try to find by exact ID
          const record = await collection.findOne({ _id: value });
          return record ? [record] : [];
        } catch (error) {
          // If ID lookup fails, fall back to regular search
          console.error("ID lookup failed, falling back to regular search:", error);
        }
      }
    
      // Create a dynamic query object for the field search
      const query: Record<string, any> = {};
    
      // Support for searching nested fields using dot notation
      query[field] = value;
    
      // Perform the search
      let results: any[] = [];
      try {
        const cursor = collection.find(query);
        
        // Handle the case when toArray is not available
        if (!cursor || typeof cursor.toArray !== 'function') {
          console.warn(`cursor.toArray is not available for query on field '${field}'`);
          return [];
        }
        
        if (typeof cursor.limit === 'function') {
          results = await cursor.limit(limit).toArray();
        } else {
          // Fallback if limit is not available
          const allResults = await cursor.toArray();
          results = allResults.slice(0, limit);
        }
      } catch (error) {
        console.error("Search failed:", error);
        results = [];
      }
    
      // If no results found with exact match, try partial text search
      if (results.length === 0) {
        try {
          // Create a regex pattern for partial matching
          // Escape special regex characters in the search value
          const escapedValue = value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
          const regexPattern = new RegExp(escapedValue, "i"); // 'i' for case-insensitive
    
          const regexQuery: Record<string, any> = {};
          regexQuery[field] = regexPattern;
    
          let regexResults: any[] = [];
          try {
            const cursor = collection.find(regexQuery);
            
            // Handle the case when toArray is not available
            if (!cursor || typeof cursor.toArray !== 'function') {
              console.warn(`cursor.toArray is not available for regex query on field '${field}'`);
              return [];
            }
            
            if (typeof cursor.limit === 'function') {
              regexResults = await cursor.limit(limit).toArray();
            } else {
              // Fallback if limit is not available
              const allResults = await cursor.toArray();
              regexResults = allResults.slice(0, limit);
            }
            return sanitizeRecordData(regexResults);
          } catch (error) {
            console.error("Regex search failed:", error);
            return [];
          }
        } catch (error) {
          console.error("Regex search failed:", error);
          return [];
        }
      }
    
      // Return sanitized results to prevent prompt injection attacks
      return sanitizeRecordData(results);
    }
  • Input schema and metadata for the FindRecord tool, used for validation and tool listing.
    {
      name: "FindRecord",
      description: "Find records in a collection by field value",
      inputSchema: {
        type: "object",
        properties: {
          collectionName: {
            type: "string",
            description: "Name of the collection to search in",
          },
          field: {
            type: "string",
            description:
              "Field name to search by (e.g., 'title', '_id', or any property)",
          },
          value: {
            type: "string",
            description: "Value to search for in the specified field",
          },
          limit: {
            type: "number",
            description: "Maximum number of records to return",
            default: 10,
          },
        },
        required: ["collectionName", "field", "value"],
      },
    },
  • index.ts:215-234 (registration)
    Registration and dispatch logic in the MCP server handler: calls the FindRecord function and formats the response.
    case "FindRecord":
      const foundRecords = await FindRecord({
        collectionName: args.collectionName as string,
        field: args.field as string,
        value: args.value as string,
        limit: args.limit as number | undefined,
      });
      // Sanitize found records to prevent prompt injection
      const sanitizedFoundRecords = sanitizeRecordData(foundRecords);
      return {
        content: [
          {
            type: "text",
            text:
              sanitizedFoundRecords.length === 0
                ? "No matching records found."
                : JSON.stringify(sanitizedFoundRecords, null, 2),
          },
        ],
      };
  • index.ts:33-33 (registration)
    Import statement for the FindRecord handler function.
    import { FindRecord } from "./tools/FindRecord.js";

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/datastax/astra-db-mcp'

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