Google Cloud Firestore MCP Server
Create a powerful Model Context Protocol (MCP) server for Google Cloud Firestore in minutes with our AI Gateway. This guide walks you through setting up seamless NoSQL database integration with real-time synchronization and instant API authentication.
About Google Cloud Firestore API
Google Cloud Firestore is a flexible, scalable NoSQL cloud database for mobile, web, and server development. It provides real-time synchronization, offline support, and seamless integration with other Google Cloud services.
Key Capabilities
- Real-time Updates: Live data synchronization
- Offline Support: Local caching and sync
- ACID Transactions: Strong consistency
- Flexible Queries: Complex filtering and sorting
- Automatic Scaling: Handle any load
- Security Rules: Fine-grained access control
- Global Distribution: Multi-region replication
- SDK Integration: Native mobile/web support
API Features
- RESTful API: Standard HTTP operations
- gRPC Support: High-performance option
- OAuth 2.0: Secure authentication
- Batch Operations: Efficient bulk updates
- Real-time Listeners: WebSocket connections
- Export/Import: Backup and migration
- Indexes: Custom query optimization
- Monitoring: Usage metrics and logs
What You Can Do with Firestore MCP Server
The MCP server transforms Firestore API into a natural language interface, enabling AI agents to:
Document Operations
-
CRUD Operations
- "Create user profile document"
- "Update product inventory"
- "Delete expired records"
- "Read customer data"
-
Batch Operations
- "Update prices for all products"
- "Delete documents older than 30 days"
- "Import user data from CSV"
- "Export collection to backup"
-
Document Search
- "Find orders from last week"
- "Search products under $50"
- "Get documents by status"
- "Query with multiple filters"
Collection Management
-
Collection Operations
- "Create new collection"
- "List all collections"
- "Count documents in collection"
- "Delete empty collections"
-
Subcollections
- "Add reviews to product"
- "Create nested structure"
- "Query across subcollections"
- "Manage hierarchical data"
-
Collection Groups
- "Query all reviews"
- "Search across subcollections"
- "Aggregate nested data"
- "Apply security rules"
Real-time Features
-
Live Listeners
- "Watch for new orders"
- "Monitor inventory changes"
- "Track user activity"
- "Sync data updates"
-
Change Feeds
- "Stream document changes"
- "Get modification history"
- "Track field updates"
- "Monitor deletions"
-
Presence System
- "Track online users"
- "Show active sessions"
- "Monitor connections"
- "Handle disconnections"
Query Operations
-
Simple Queries
- "Get active users"
- "Find completed orders"
- "List featured products"
- "Search by category"
-
Compound Queries
- "Find orders over $100 from California"
- "Get products in stock under $50"
- "Search users by age and location"
- "Filter by multiple conditions"
-
Aggregation Queries
- "Count total orders"
- "Sum revenue by month"
- "Average product rating"
- "Group by category"
Data Management
-
Transactions
- "Transfer funds between accounts"
- "Update inventory atomically"
- "Increment counters safely"
- "Batch atomic updates"
-
Data Validation
- "Enforce field types"
- "Validate required fields"
- "Check value ranges"
- "Apply business rules"
-
Backup & Restore
- "Export database backup"
- "Schedule automatic backups"
- "Restore from point in time"
- "Migrate between projects"
Security & Access
-
Security Rules
- "Configure access control"
- "Set user permissions"
- "Validate data writes"
- "Enforce rate limits"
-
Authentication
- "Integrate with Firebase Auth"
- "Custom authentication"
- "Service account access"
- "API key management"
-
Field-level Security
- "Restrict sensitive fields"
- "Role-based access"
- "Conditional visibility"
- "Audit data access"
Analytics & Monitoring
-
Usage Metrics
- "Show read/write operations"
- "Monitor bandwidth usage"
- "Track active connections"
- "Calculate costs"
-
Performance Analysis
- "Identify slow queries"
- "Optimize indexes"
- "Monitor latency"
- "Track hotspots"
-
Audit Logs
- "Track data changes"
- "Monitor admin actions"
- "Review access logs"
- "Generate reports"
Prerequisites
- Access to Cequence AI Gateway
- Google Cloud Project
- Firestore API enabled
- Service account credentials
Step 1: Configure Firestore API Access
1.1 Enable Firestore API
- Go to Google Cloud Console
- Navigate to Firestore
- Click Create Database
- Choose mode:
- Native Mode (recommended)
- Datastore Mode
1.2 Create Service Account
- Go to IAM & Admin Service Accounts
- Click Create Service Account
- Configure:
- Name: "AI Gateway Firestore"
- Role: Cloud Datastore User or Owner
- Create and download JSON key
1.3 Configure Database
- Select database location (multi-region recommended)
- Configure security rules
- Set up indexes if needed
- Enable audit logs (optional)
1.4 OAuth 2.0 Setup (Alternative)
For user-context access:
- Create OAuth 2.0 credentials
- Configure consent screen
- Add authorized redirect URIs
Step 2-4: Standard Setup
Follow standard steps to access AI Gateway, find Firestore API, and create MCP server.
Step 5: Configure API Endpoints
- Base URL:
https://firestore.googleapis.com/v1
- Project ID: Your GCP project ID
- Database ID:
(default)
or custom - Click Next
Step 6: MCP Server Configuration
- Name: "Firestore Database"
- Description: "NoSQL real-time database"
- Request Timeout: 60 seconds
- Click Next
Step 7: Configure Authentication
- Authentication Type: Service Account
- Upload service account JSON key
- Or configure OAuth 2.0:
- Client ID and Secret
- Required scopes
- Test connection
Available Firestore API Operations
Document APIs
-
Document Operations
- Create document
- Get document
- Update document
- Delete document
- List documents
-
Batch Operations
- Batch get
- Batch write
- Batch delete
Collection APIs
- Collection Operations
- List collections
- Query collection
- Add to collection
- Clear collection
Query APIs
- Query Operations
- Simple queries
- Compound queries
- Collection group queries
- Aggregation queries
Transaction APIs
- Transaction Operations
- Begin transaction
- Commit transaction
- Rollback transaction
Real-time APIs
- Listen Operations
- Document listeners
- Collection listeners
- Query listeners
Admin APIs
- Database Operations
- Export database
- Import database
- Create indexes
- Backup/restore
Step 8-10: Complete Setup
Configure security settings, choose deployment options, and deploy your server.
Using Your Firestore MCP Server
With Claude Desktop
{
"servers": {
"firestore": {
"url": "your-mcp-server-url",
"auth": {
"type": "service-account",
"credentials": "base64-encoded-service-account-key"
},
"config": {
"project_id": "your-project-id",
"database_id": "(default)"
}
}
}
}
Natural Language Commands
- "Create a new user document with email and name"
- "Find all orders placed today with status pending"
- "Update product inventory when order is placed"
- "Watch for changes in the messages collection"
- "Count total active users in the system"
API Integration Example
// Initialize MCP client
const mcpClient = new MCPClient({
serverUrl: 'your-mcp-server-url',
auth: {
type: 'service-account',
credentials: serviceAccountKey
}
});
// Create a document
const user = await mcpClient.firestore.createDocument({
collection: 'users',
documentId: 'user-123', // Optional, auto-generate if not provided
data: {
email: 'john.doe@example.com',
displayName: 'John Doe',
profile: {
bio: 'Software developer',
location: 'San Francisco, CA',
interests: ['coding', 'hiking', 'photography']
},
metadata: {
createdAt: new Date().toISOString(),
lastLogin: new Date().toISOString(),
accountType: 'premium'
},
settings: {
notifications: true,
darkMode: false,
language: 'en'
}
}
});
console.log(`Created user: ${user.name}`);
// Query documents
const activeUsers = await mcpClient.firestore.query({
collection: 'users',
where: [
{ field: 'metadata.accountType', op: '==', value: 'premium' },
{ field: 'settings.notifications', op: '==', value: true }
],
orderBy: [
{ field: 'metadata.lastLogin', direction: 'desc' }
],
limit: 20
});
console.log(`Found ${activeUsers.documents.length} active premium users`);
// Compound query with multiple conditions
const orders = await mcpClient.firestore.query({
collection: 'orders',
where: [
{ field: 'status', op: '==', value: 'pending' },
{ field: 'total', op: '>=', value: 100 },
{ field: 'createdAt', op: '>=', value: new Date(Date.now() - 24*60*60*1000) }
],
orderBy: [
{ field: 'total', direction: 'desc' }
]
});
// Real-time listener
const unsubscribe = await mcpClient.firestore.listen({
collection: 'messages',
where: [
{ field: 'chatRoom', op: '==', value: 'general' }
],
orderBy: [
{ field: 'timestamp', direction: 'desc' }
],
limit: 50,
onSnapshot: (snapshot) => {
snapshot.docChanges.forEach(change => {
if (change.type === 'added') {
console.log('New message:', change.doc.data());
} else if (change.type === 'modified') {
console.log('Message updated:', change.doc.data());
} else if (change.type === 'removed') {
console.log('Message deleted:', change.doc.id);
}
});
},
onError: (error) => {
console.error('Listen error:', error);
}
});
// Transaction example
const transferResult = await mcpClient.firestore.runTransaction(async (transaction) => {
// Read documents
const fromAccount = await transaction.get('accounts/account-123');
const toAccount = await transaction.get('accounts/account-456');
const fromBalance = fromAccount.data().balance;
const toBalance = toAccount.data().balance;
const transferAmount = 100;
if (fromBalance < transferAmount) {
throw new Error('Insufficient funds');
}
// Update documents atomically
transaction.update('accounts/account-123', {
balance: fromBalance - transferAmount,
lastTransaction: new Date().toISOString()
});
transaction.update('accounts/account-456', {
balance: toBalance + transferAmount,
lastTransaction: new Date().toISOString()
});
// Create transaction record
transaction.create('transactions/txn-' + Date.now(), {
from: 'account-123',
to: 'account-456',
amount: transferAmount,
timestamp: new Date().toISOString(),
type: 'transfer'
});
return { success: true, amount: transferAmount };
});
// Batch write operations
const batch = mcpClient.firestore.batch();
// Update multiple products
const products = [
{ id: 'prod-1', price: 29.99, sale: true },
{ id: 'prod-2', price: 49.99, sale: true },
{ id: 'prod-3', price: 19.99, sale: true }
];
products.forEach(product => {
batch.update(`products/${product.id}`, {
price: product.price,
sale: product.sale,
updatedAt: new Date().toISOString()
});
});
// Add audit log
batch.create('audit_logs/log-' + Date.now(), {
action: 'bulk_price_update',
products: products.map(p => p.id),
timestamp: new Date().toISOString(),
user: 'admin@company.com'
});
await batch.commit();
// Collection group query
const allReviews = await mcpClient.firestore.collectionGroupQuery({
collectionId: 'reviews',
where: [
{ field: 'rating', op: '>=', value: 4 },
{ field: 'verified', op: '==', value: true }
],
orderBy: [
{ field: 'createdAt', direction: 'desc' }
],
limit: 100
});
console.log(`Found ${allReviews.documents.length} positive reviews across all products`);
// Aggregation query
const stats = await mcpClient.firestore.aggregateQuery({
collection: 'orders',
where: [
{ field: 'status', op: '==', value: 'completed' },
{ field: 'createdAt', op: '>=', value: '2025-01-01' }
],
aggregations: [
{ type: 'count', alias: 'totalOrders' },
{ type: 'sum', field: 'total', alias: 'totalRevenue' },
{ type: 'average', field: 'total', alias: 'averageOrderValue' }
]
});
console.log(`Orders Stats: ${stats.totalOrders} orders, $${stats.totalRevenue} revenue`);
// Subcollection operations
const product = 'products/prod-123';
const review = await mcpClient.firestore.createDocument({
collection: `${product}/reviews`,
data: {
userId: 'user-456',
rating: 5,
title: 'Great product!',
comment: 'Exceeded my expectations',
verified: true,
helpful: 0,
images: ['review-img-1.jpg', 'review-img-2.jpg'],
createdAt: new Date().toISOString()
}
});
// Complex nested data structure
const project = await mcpClient.firestore.createDocument({
collection: 'projects',
data: {
name: 'Website Redesign',
client: 'Acme Corp',
status: 'in_progress',
team: {
lead: 'user-123',
members: ['user-456', 'user-789'],
roles: {
'user-123': 'Project Manager',
'user-456': 'Designer',
'user-789': 'Developer'
}
},
milestones: [
{
id: 'ms-1',
title: 'Design Phase',
dueDate: '2025-02-15',
status: 'completed',
tasks: [
{ id: 't-1', title: 'Wireframes', assignee: 'user-456', done: true },
{ id: 't-2', title: 'Mockups', assignee: 'user-456', done: true }
]
},
{
id: 'ms-2',
title: 'Development Phase',
dueDate: '2025-03-30',
status: 'in_progress',
tasks: [
{ id: 't-3', title: 'Frontend', assignee: 'user-789', done: false },
{ id: 't-4', title: 'Backend', assignee: 'user-789', done: false }
]
}
],
budget: {
total: 50000,
spent: 15000,
categories: {
design: 10000,
development: 30000,
testing: 5000,
deployment: 5000
}
}
}
});
// Geolocation query
const nearbyStores = await mcpClient.firestore.query({
collection: 'stores',
where: [
{ field: 'location.geopoint', op: 'near', value: {
center: new mcpClient.firestore.GeoPoint(37.7749, -122.4194), // San Francisco
radius: 10000 // 10km in meters
}}
],
orderBy: [
{ field: 'location.geopoint', direction: 'asc' } // Ordered by distance
],
limit: 10
});
// Security rules simulation
const testAccess = await mcpClient.firestore.testSecurityRules({
resource: 'users/user-123',
operation: 'update',
auth: {
uid: 'user-456',
token: {
email: 'test@example.com',
email_verified: true
}
},
data: {
displayName: 'New Name'
}
});
console.log(`Access ${testAccess.allowed ? 'allowed' : 'denied'}: ${testAccess.reason}`);
// Export database
const exportOperation = await mcpClient.firestore.exportDatabase({
outputUriPrefix: 'gs://my-bucket/firestore-backups/2025-01-30',
collectionIds: ['users', 'orders', 'products'] // Specific collections or empty for all
});
console.log(`Export started: ${exportOperation.name}`);
// Monitor export progress
const exportStatus = await mcpClient.firestore.getOperation({
name: exportOperation.name
});
// Create composite index
const index = await mcpClient.firestore.createIndex({
collectionGroup: 'orders',
fields: [
{ fieldPath: 'status', order: 'ASCENDING' },
{ fieldPath: 'createdAt', order: 'DESCENDING' }
]
});
// Enable real-time presence
const presence = await mcpClient.firestore.createDocument({
collection: 'presence',
documentId: 'user-123',
data: {
online: true,
lastSeen: new Date().toISOString(),
status: 'active'
}
});
// Set up disconnect handler
await mcpClient.firestore.onDisconnect({
document: 'presence/user-123',
update: {
online: false,
lastSeen: new Date().toISOString()
}
});
Common Use Cases
Mobile/Web Apps
- User profiles and settings
- Real-time chat and messaging
- Collaborative editing
- Offline-first applications
E-commerce
- Product catalogs
- Shopping carts
- Order management
- Inventory tracking
Gaming
- Player profiles
- Leaderboards
- Game state
- Matchmaking
IoT & Sensor Data
- Device management
- Sensor readings
- Real-time monitoring
- Event logging
Best Practices
-
Data Modeling:
- Denormalize for performance
- Use subcollections wisely
- Consider query patterns
- Avoid deep nesting
-
Performance:
- Create appropriate indexes
- Limit document size (1MB max)
- Use pagination for large results
- Cache frequently accessed data
-
Security:
- Write comprehensive security rules
- Validate data on write
- Use least privilege access
- Audit sensitive operations
Troubleshooting
Common Issues
-
Permission Errors
- Check service account roles
- Verify security rules
- Review OAuth scopes
- Confirm project access
-
Query Performance
- Add composite indexes
- Reduce result size
- Optimize where clauses
- Use query explain
-
Real-time Issues
- Check listener limits
- Handle reconnection
- Monitor bandwidth
- Implement error retry
Getting Help
- Documentation: AI Gateway Docs
- Support: support@cequence.ai
- Firestore Docs: firebase.google.com/docs/firestore