Skip to main content
Glama
gemini-dk

Firebase MCP Server

by gemini-dk

firestore_list_documents

Retrieve documents from a Firestore collection with optional filtering, pagination, and limit controls for data management.

Instructions

List documents from a Firestore collection with optional filtering

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
collectionYesCollection name
filtersNoArray of filter conditions
limitNoNumber of documents to return
pageTokenNoToken for pagination to get the next page of results

Implementation Reference

  • Core handler function for firestore_list_documents tool: queries Firestore collection with optional filters, pagination via pageToken, converts timestamps, generates console URLs, and returns paginated document list with total count.
    export async function listDocuments(collection: string, filters: Array<{ field: string, operator: FirebaseFirestore.WhereFilterOp, value: any }> = [], limit: number = 20, pageToken?: string) {
      const projectId = getProjectId();
      try {
        if (!db) {
          return { content: [{ type: 'text', text: 'Firebase is not initialized. SERVICE_ACCOUNT_KEY_PATH environment variable is required.' }], isError: true };
        }
        
        const collectionRef = db.collection(collection);
        let filteredQuery: Query = collectionRef;
        for (const filter of filters) {
          let filterValue = filter.value;
          if (typeof filterValue === 'string' && !isNaN(Date.parse(filterValue))) {
            filterValue = Timestamp.fromDate(new Date(filterValue));
          }
          filteredQuery = filteredQuery.where(filter.field, filter.operator, filterValue);
        }
        
        // Apply pageToken if provided
        if (pageToken) {
          const startAfterDoc = await collectionRef.doc(pageToken).get();
          filteredQuery = filteredQuery.startAfter(startAfterDoc);
        }
    
        // Get total count of documents matching the filter
        const countSnapshot = await filteredQuery.get();
        const totalCount = countSnapshot.size;
    
        // Get the first 'limit' documents
        const limitedQuery = filteredQuery.limit(limit);
        const snapshot = await limitedQuery.get();
    
        if (snapshot.empty) {
          return { content: [{ type: 'text', text: 'No matching documents found' }], isError: true };
        }
        
        const documents = snapshot.docs.map((doc: any) => {
          const data = doc.data();
          convertTimestampsToISO(data);
          const consoleUrl = `https://console.firebase.google.com/project/${projectId}/firestore/data/${collection}/${doc.id}`;
          return { id: doc.id, url: consoleUrl, document: data };
        });
        
        return { 
          content: [{
            type: 'text', 
            text: JSON.stringify({
              totalCount,
              documents,
              pageToken: documents.length > 0 ? documents[documents.length - 1].id : null,
              hasMore: totalCount > limit
            })
          }]
        };
      } catch (error) {
        return { content: [{ type: 'text', text: `Error listing documents: ${(error as Error).message}` }], isError: true };
      }
    }
  • Input schema definition for the firestore_list_documents tool, including parameters for collection, filters, limit, and pageToken.
    name: 'firestore_list_documents',
    description: 'List documents from a Firestore collection with optional filtering',
    inputSchema: {
      type: 'object',
      properties: {
        collection: {
          type: 'string',
          description: 'Collection name'
        },
        filters: {
          type: 'array',
          description: 'Array of filter conditions',
          items: {
            type: 'object',
            properties: {
              field: {
                type: 'string',
                description: 'Field name to filter'
              },
              operator: {
                type: 'string',
                description: 'Comparison operator'
              },
              value: {
                type: 'any',
                description: 'Value to compare against (use ISO format for dates)'
              }
            },
            required: ['field', 'operator', 'value']
          }
        },
      limit: {
        type: 'number',
        description: 'Number of documents to return',
        default: 20
      },
      pageToken: {
        type: 'string',
        description: 'Token for pagination to get the next page of results'
      }
      },
      required: ['collection']
    }
  • src/index.ts:231-237 (registration)
    Tool dispatch/registration in the CallToolRequestSchema handler: maps tool call to the listDocuments implementation.
    case 'firestore_list_documents':
      return listDocuments(
        args.collection as string,
        args.filters as Array<{ field: string, operator: FirebaseFirestore.WhereFilterOp, value: any }>,
        args.limit as number,
        args.pageToken as string | undefined
      );
  • Helper function used in listDocuments to convert Firestore Timestamp fields to ISO strings for JSON output.
    function convertTimestampsToISO(data: any) {
      for (const key in data) {
        if (data[key] instanceof Timestamp) {
          data[key] = data[key].toDate().toISOString();
        }
      }
      return data;
    }
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 'optional filtering' which hints at query capabilities, but fails to describe critical behaviors: whether this is a read-only operation (implied but not stated), pagination mechanics (only hinted by the 'pageToken' parameter), rate limits, authentication requirements, error conditions, or the format of returned data. For a database query tool with zero annotation coverage, this leaves significant gaps.

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 immediately conveys the core functionality. Every word earns its place: 'List documents' (action), 'from a Firestore collection' (resource), 'with optional filtering' (key capability). There's no redundancy or unnecessary elaboration, making it perfectly concise and well-structured.

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 4 parameters, no annotations, and no output schema, the description is insufficiently complete. It doesn't explain what the tool returns (document format, metadata), how pagination works, error handling, or authentication requirements. While the schema covers parameter details, the description fails to provide the broader context needed for effective tool 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?

The schema description coverage is 100%, providing complete documentation for all 4 parameters. The description adds minimal value beyond the schema by mentioning 'optional filtering' which corresponds to the 'filters' parameter, but doesn't explain filter syntax, operator options, or practical usage examples. Since the schema does the heavy lifting, the baseline score of 3 is appropriate.

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 verb ('List') and resource ('documents from a Firestore collection'), making the purpose immediately understandable. It distinguishes from siblings like 'firestore_get_document' (single document) and 'firestore_list_collections' (collections rather than documents). However, it doesn't specify the scope (e.g., all documents vs. paginated results) which prevents a perfect score.

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. It doesn't mention when to choose 'firestore_list_documents' over 'firestore_get_document' (single document retrieval) or 'firestore_list_collections' (listing collections). There's also no mention of prerequisites like authentication or collection existence, leaving the agent with insufficient context for decision-making.

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/gemini-dk/mcp-server-firebase'

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