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";
Behavior2/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 mentions searching by field value but doesn't cover important aspects like whether it's case-sensitive, supports partial matches, returns errors for invalid collections, or has pagination/rate limits. This leaves significant gaps for a search tool.

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 that directly states the tool's purpose without any fluff or redundancy. It's appropriately sized and front-loaded, making it easy to understand quickly.

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 search tool with 4 parameters, no annotations, and no output schema, the description is incomplete. It doesn't explain return values, error conditions, or behavioral nuances, leaving the agent with insufficient context to use the tool effectively beyond basic parameter passing.

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 4 parameters thoroughly. The description adds no additional meaning beyond what's in the schema (e.g., it doesn't explain search semantics or provide examples beyond the basic concept), meeting the baseline for high schema coverage.

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 action ('Find records') and target ('in a collection by field value'), providing specific verb+resource. However, it doesn't differentiate from sibling tools like 'ListRecords' or 'GetRecord', which might offer similar search/list functionality, 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 like 'ListRecords' or 'GetRecord', nor does it mention prerequisites or exclusions. It only states what the tool does, not when it's appropriate.

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

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

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