A powerful Model Context Protocol (MCP) server that provides comprehensive integration with Google Workspace (Drive, Sheets, Docs, Forms, and Apps Script). This server enables AI assistants and applications to seamlessly interact with Google services through a standardized, secure interface.
You'll need a Google account and Node.js 18+ installed.
-
Google Cloud Setup
- Create project at Google Cloud Console
- Enable APIs: Drive, Sheets, Docs, Forms, Apps Script
- Create OAuth credentials and download as
gcp-oauth.keys.json
-
Installation & Authentication
# Clone and install git clone https://github.com/AojdevStudio/gdrive.git cd gdrive npm install && npm run build # Set up credentials mkdir -p credentials cp /path/to/gcp-oauth.keys.json credentials/ # Generate encryption key and authenticate export GDRIVE_TOKEN_ENCRYPTION_KEY=$(openssl rand -base64 32) node ./dist/index.js auth
-
Start Server
node ./dist/index.js
# 1) Prepare bind mounts on the HOST
mkdir -p credentials logs data
cp /path/to/gcp-oauth.keys.json credentials/
# 2) Ensure encryption key is set (32-byte base64)
# Option A: put it in .env at the project root
# GDRIVE_TOKEN_ENCRYPTION_KEY=<your-32-byte-base64>
# Option B: export in your shell before compose
# export GDRIVE_TOKEN_ENCRYPTION_KEY=$(openssl rand -base64 32)
# 3) Start with Docker Compose (includes Redis)
docker compose up -d --build # or: docker-compose up -d --build
# 4) Verify containers
docker compose ps # expect both services to be 'Up (healthy)'
# 5) Check recent server logs (now include full error details)
docker compose logs gdrive-mcp -n 100 --no-color | cat
# 6) Health check (inside container)
docker compose exec gdrive-mcp-server node dist/index.js health
π Complete Docker Guide β
Major Version Update: Google Drive MCP Server v2.0.0 introduces significant architectural improvements that require migration from previous versions.
We've consolidated 41+ individual tools into 5 operation-based tools, following the 2025 MCP architecture patterns from HOW2MCP.
Before (v1.x): Each operation was a separate tool
{
"name": "listSheets",
"args": { "spreadsheetId": "abc123" }
}
After (v2.0.0): Operations are parameters within consolidated tools
{
"name": "sheets",
"args": {
"operation": "list",
"spreadsheetId": "abc123"
}
}
- 88% Reduction in Tool Count (41+ β 5) - LLMs can select the right tool faster
- Better Type Safety - Zod discriminated unions for reliable operation routing
- Cleaner API - Logical grouping by service (sheets, drive, forms, docs, batch)
- Future-Proof - Follows 2025 MCP architecture best practices
π Complete Migration Guide - Step-by-step instructions for updating your code
All existing tool calls must be updated to use the new operation-based format. See the migration guide for comprehensive before/after examples covering all 32 operations.
The server features automatic OAuth token refresh with enterprise-grade encryption - authenticate once, works forever.
# Local setup
export GDRIVE_TOKEN_ENCRYPTION_KEY=$(openssl rand -base64 32)
node ./dist/index.js auth
# Docker setup
./scripts/auth.sh
π Complete Authentication Guide β
Local Setup:
{
"mcpServers": {
"gdrive": {
"command": "node",
"args": ["/absolute/path/to/gdrive-mcp/dist/index.js"],
"env": { "GDRIVE_TOKEN_ENCRYPTION_KEY": "your-key" }
}
}
}
Docker Setup (Recommended):
{
"mcpServers": {
"gdrive": {
"command": "docker",
"args": ["exec", "-i", "gdrive-mcp-server", "node", "dist/index.js"]
}
}
}
π Complete Integration Guide β
- Automatic OAuth Token Refresh - Eliminates manual re-authentication
- AES-256-GCM Encryption - Secure token storage at rest
- Comprehensive Audit Trail - Full logging of all authentication events
- Health Monitoring - Real-time token status and system health checks
- File Management - Create, read, update, delete files and folders
- Advanced Search - Natural language queries with intelligent filtering
- Batch Operations - Process multiple files efficiently in single operations
- Format Conversion - Automatic export of Google Workspace files to readable formats
- Data Access - Read and write sheet data with A1 notation support
- Sheet Management - Create, rename, delete, and list sheets; update cells; append rows
- Formula Automation - Apply formulas to specific cells with
updateCellsWithFormula
- Cell Formatting - Apply bold/italic text, colors, and number formats with
formatCells
- Conditional Formatting - Highlight trends with custom rules (e.g., green gains, red losses)
- Layout Controls - Freeze header rows/columns and adjust column widths for better readability
- CSV Export - Automatic conversion for data analysis
Add a SUM formula to total a column:
await updateCellsWithFormula({
spreadsheetId: "your-spreadsheet-id",
range: "Sheet1!D25",
formula: "=SUM(D2:D24)"
});
Apply formulas to multiple cells (with relative references):
// This applies the formula to cells E2:E25
// Google Sheets automatically adjusts relative references
// So E2 gets =D2*1.1, E3 gets =D3*1.1, etc.
await updateCellsWithFormula({
spreadsheetId: "your-spreadsheet-id",
range: "E2:E25",
formula: "=D2*1.1"
});
Calculate running totals:
await updateCellsWithFormula({
spreadsheetId: "your-spreadsheet-id",
range: "Budget!F10",
formula: "=SUM(F2:F9)"
});
Use VLOOKUP for data matching:
await updateCellsWithFormula({
spreadsheetId: "your-spreadsheet-id",
range: "Sheet1!C2",
formula: "=VLOOKUP(A2,Prices!A:B,2,FALSE)"
});
When using updateCellsWithFormula
, be aware of these security considerations:
- Formula Execution Context: Formulas execute within Google Sheets' security sandbox
- External URL Access: User-crafted formulas can access external URLs via functions like
IMPORTXML
,IMPORTDATA
, orIMPORTHTML
- Input Validation: If accepting formula input from users in your application:
- Validate formula content before passing to the MCP server
- Consider restricting dangerous functions (IMPORTXML, IMPORTHTML, etc.)
- Implement allowlists for permitted functions
- Permission Model: The MCP server respects Google Drive file permissions - users can only update sheets they have edit access to
- Data Exposure: Be cautious with formulas that might expose sensitive data through external requests
Example validation pattern:
// Validate user-provided formulas
function isSafeFormula(formula) {
const dangerousFunctions = ['IMPORTXML', 'IMPORTHTML', 'IMPORTDATA', 'IMAGE'];
const upperFormula = formula.toUpperCase();
return !dangerousFunctions.some(fn => upperFormula.includes(fn));
}
// Only allow safe formulas
if (isSafeFormula(userFormula)) {
await updateCellsWithFormula({ spreadsheetId, range, formula: userFormula });
} else {
throw new Error('Formula contains potentially unsafe functions');
}
Make headers bold with gray background:
await formatCells({
spreadsheetId: "your-spreadsheet-id",
range: "Sheet1!A1:Z1",
format: {
bold: true,
backgroundColor: {
red: 0.85,
green: 0.85,
blue: 0.85
}
}
});
Apply currency formatting:
await formatCells({
spreadsheetId: "your-spreadsheet-id",
range: "Sheet1!C2:C100",
format: {
numberFormat: {
type: "CURRENCY",
pattern: "$#,##0.00"
}
}
});
Highlight warnings in red:
await formatCells({
spreadsheetId: "your-spreadsheet-id",
range: "Sheet1!A10:D10",
format: {
foregroundColor: {
red: 0.8,
green: 0.2,
blue: 0.2
},
bold: true
}
});
- Document Creation - Create documents with content and formatting
- Text Operations - Insert, replace, and style text at specific positions
- Table Management - Insert tables with custom dimensions
- Rich Formatting - Apply bold, italic, underline, colors, and font sizes
- Form Creation - Build forms with titles, descriptions, and various question types
- Question Types - Text, multiple choice, checkboxes, linear scales, dates, and more
- Response Management - Retrieve and analyze form responses
- Validation Support - Required fields and input validation
- Script Viewing - Read-only access to Apps Script project source code
- Multi-File Support - Handle JavaScript, HTML, and JSON files
- Syntax Highlighting - Automatic code formatting in responses
- Redis Caching - High-performance caching with automatic invalidation
- Performance Monitoring - Real-time metrics and statistics tracking
- Structured Logging - Winston-based logging with file rotation
- Docker Support - Containerized deployment with Docker Compose
graph TB
A[MCP Client] --> B[MCP Server]
B --> C[Auth Manager]
B --> D[Token Manager]
B --> E[Cache Manager]
B --> F[Performance Monitor]
C --> G[Google OAuth 2.0]
D --> H[Encrypted Token Storage]
E --> I[Redis Cache]
B --> J[Google Drive API]
B --> K[Google Sheets API]
B --> L[Google Docs API]
B --> M[Google Forms API]
B --> N[Google Apps Script API]
F --> O[Winston Logger]
style B fill:#e1f5fe
style C fill:#f3e5f5
style D fill:#f3e5f5
style E fill:#e8f5e8
style F fill:#fff3e0
- index.ts - Main MCP server implementation with consolidated tool handlers
- AuthManager - OAuth 2.0 authentication with automatic token refresh
- TokenManager - Secure encrypted token storage and lifecycle management
- CacheManager - Redis-based caching with intelligent invalidation
- PerformanceMonitor - Real-time performance tracking and metrics collection
Following HOW2MCP 2025 best practices, the server implements an operation-based tool pattern:
Design Pattern:
// Each service has ONE tool with multiple operations
{
name: "sheets",
args: {
operation: "list" | "read" | "create" | ..., // Operation discriminator
spreadsheetId: "...", // Common parameters
// ... operation-specific parameters
}
}
Key Architectural Benefits:
- Zod Discriminated Unions - Type-safe operation routing with compile-time validation
- Centralized Handlers - Single tool registration point per service prevents overwriting
- Cleaner Codebase - Reduced duplication with shared validation and error handling
- Better LLM Performance - 88% reduction in tool count (41+ β 5) enables faster tool selection
File Structure:
src/
sheets/
sheets-handler.ts # Operation router
sheets-schemas.ts # Zod discriminated union schemas
drive/
drive-handler.ts
drive-schemas.ts
forms/, docs/, batch/ # Similar structure
This architecture ensures maintainability, type safety, and optimal LLM integration performance.
The server provides 5 consolidated operation-based tools with 32 total operations:
Unified tool for all Google Sheets functionality:
list
- List all sheets in a spreadsheetread
- Read data from a specific rangecreate
- Create a new sheet in a spreadsheetrename
- Rename an existing sheetdelete
- Delete a sheetupdate
- Update cell values in a rangeupdateFormula
- Apply formulas to cellsformat
- Apply formatting (bold, colors, number formats)conditionalFormat
- Add conditional formatting rulesappend
- Append rows to a sheetfreeze
- Freeze header rows/columnssetColumnWidth
- Adjust column widths
Unified tool for file and folder management:
search
- Search files with natural language queriesenhancedSearch
- Advanced search with filtersread
- Read file contentscreate
- Create new filesupdate
- Update existing filescreateFolder
- Create new foldersbatch
- Batch file operations
Unified tool for form creation and management:
create
- Create new formsget
- Retrieve form detailsaddQuestion
- Add questions to formslistResponses
- Get form responses
Unified tool for document manipulation:
create
- Create new documentsinsertText
- Insert text at positionsreplaceText
- Find and replace textapplyTextStyle
- Apply formatting (bold, italic, colors)insertTable
- Insert tables
Unified tool for efficient multi-file processing:
create
- Create multiple filesupdate
- Update multiple filesdelete
- Delete multiple filesmove
- Move multiple files
- MCP Resource Access:
gdrive:///<file_id>
URIs for file access
π Complete API Documentation β
If you're migrating from v1.x, each old tool maps to an operation parameter:
Old Tool (v1.x) | New Tool (v2.0.0) | Operation |
---|---|---|
listSheets |
sheets |
"list" |
readSheet |
sheets |
"read" |
createSheet |
sheets |
"create" |
updateCells |
sheets |
"update" |
...and 28 more | See Migration Guide |
π Complete Migration Guide with All 32 Operations β
- Advanced Search: Natural language queries with intelligent filtering
- Batch Operations: Process multiple files efficiently in single operations
- Format Conversion: Automatic export (DocsβMarkdown, SheetsβCSV, etc.)
- Rich Text Editing: Full document formatting with styles, tables, and positioning
- Form Builder: Complete form creation with 8+ question types and validation
- Apps Script: Read-only access to Google Apps Script project source code
- AES-256-GCM Encryption - All tokens encrypted at rest
- Automatic Token Refresh - No manual re-authentication needed
- Comprehensive Audit Trail - Full logging of authentication events
- Health Monitoring - Real-time token status checks
π Security Documentation β
Before upgrading to v2.0.0, migrate your existing tokens to the new versioned encryption system:
# 1. Backup existing tokens (automatic, but manual backup recommended)
cp .gdrive-mcp-tokens.json .gdrive-mcp-tokens.backup.json
# 2. Run migration script
node scripts/migrate-tokens.js
# 3. Verify migration success
node dist/index.js verify-keys
For enhanced security, rotate your encryption keys periodically:
# Generate new key and re-encrypt all tokens
node dist/index.js rotate-key
# Verify all tokens work with new key
node dist/index.js verify-keys
Variable | Description | Default |
---|---|---|
GDRIVE_TOKEN_ENCRYPTION_KEY |
Base64-encoded 32-byte encryption key | Auto-generated |
GDRIVE_KEY_DERIVATION_ITERATIONS |
PBKDF2 iterations for key strengthening | 100000 |
GDRIVE_ROTATION_BACKUP_COUNT |
Number of backup files to retain | 5 |
# Key management commands
node dist/index.js rotate-key # Rotate encryption key
node dist/index.js verify-keys # Verify all tokens
node dist/index.js migrate-tokens # Migrate legacy tokens
node dist/index.js key-status # Show key version and health
Token Decryption Failures:
# Check key status and version compatibility
node dist/index.js key-status
# Restore from backup if needed
cp .gdrive-mcp-tokens.backup.json .gdrive-mcp-tokens.json
node dist/index.js verify-keys
Performance Issues:
- Key rotation should complete in < 30 seconds for 100 tokens
- PBKDF2 overhead should be < 5% compared to static key
- Memory usage remains stable during rotation operations
π Complete Key Rotation Guide β
# Check health status
node ./dist/index.js health
Health States: π’ HEALTHY | π‘ DEGRADED | π΄ UNHEALTHY
π Health Monitoring Guide β
// Natural language search with drive tool
await callTool("drive", {
operation: "search",
query: "spreadsheets modified last week"
});
// Create document with docs tool
await callTool("docs", {
operation: "create",
title: "Project Report",
content: "# Project Overview\n\nThis document outlines..."
});
// Batch file operations with batch tool
await callTool("batch", {
operation: "create",
operations: [
{ type: "create", name: "report.txt", content: "..." },
{ type: "create", name: "notes.txt", content: "..." }
]
});
// Update spreadsheet cells with sheets tool
await callTool("sheets", {
operation: "update",
spreadsheetId: "abc123",
range: "Sheet1!A1:B2",
values: [["Name", "Age"], ["John", 30]]
});
π Complete Examples & Code Samples β
- AES-256-GCM Encryption - All tokens encrypted at rest
- Automatic Token Refresh - Eliminates re-authentication
- Comprehensive Audit Trail - Full security event logging
- Robust Error Handling - Circuit breaker and graceful degradation
π Complete Security Documentation β
Variable | Description | Required |
---|---|---|
GDRIVE_TOKEN_ENCRYPTION_KEY |
32-byte base64 encryption key | β |
GDRIVE_KEY_DERIVATION_ITERATIONS |
PBKDF2 iterations for key strengthening (min: 100000) | β |
GDRIVE_ROTATION_BACKUP_COUNT |
Number of backup files to retain during rotation | β |
REDIS_URL |
Redis cache connection URL | β |
LOG_LEVEL |
Winston logging level (info/debug) | β |
GDRIVE_TOKEN_ENCRYPTION_KEY=your-32-byte-base64-key
GDRIVE_KEY_DERIVATION_ITERATIONS=100000
GDRIVE_ROTATION_BACKUP_COUNT=5
REDIS_URL=redis://localhost:6379
LOG_LEVEL=info
π Complete Configuration Guide β
Token Issues:
# Check health and re-authenticate if needed
node dist/index.js health
./scripts/auth.sh
Docker Issues:
# Check logs and verify mounts
docker compose logs gdrive-mcp -n 100 --no-color | cat
docker compose exec gdrive-mcp-server ls -la /credentials/
docker compose exec gdrive-mcp-server ls -la /app/logs/
# If the server restarts repeatedly:
# - Confirm key present in container env
docker inspect gdrive-mcp-server --format='{{range .Config.Env}}{{println .}}{{end}}' | grep GDRIVE_TOKEN_ENCRYPTION_KEY
# - Ensure host bind-mount directories exist
ls -la credentials logs data
# - Health check from inside the container
docker compose exec gdrive-mcp-server node dist/index.js health
Notes on Logging:
- Error objects are fully serialized (name, message, stack) and written to
logs/error.log
andlogs/combined.log
. - Audit trail is written to
logs/gdrive-mcp-audit.log
. Directories are auto-created if missing.
Token Decryption Compatibility:
- Tokens are encrypted with AES-256-GCM using a key derived (PBKDF2) from your base key in
GDRIVE_TOKEN_ENCRYPTION_KEY
. - As long as the same base key is provided, tokens can be decrypted across host and Docker.
Performance Issues:
# Check Redis and system resources
redis-cli ping
docker stats gdrive-mcp-server
π Complete Troubleshooting Guide β
# Clone and install
git clone <repository-url>
cd gdrive-mcp-server
npm install
# Set up environment
cp .env.example .env # Add your encryption key
npm run build
# Development with auto-rebuild
npm run watch
npm run build
- Compile TypeScriptnpm run watch
- Auto-rebuild on changesnpm test
- Run test suitenpm run lint
- Code quality checks
π Complete Development Guide β
We welcome contributions! Areas where you can help:
- π Bug Fixes - Improve stability
- β¨ Features - New Google Workspace integrations
- π Documentation - Enhance guides and examples
- π§ Performance - Optimize caching and API usage
- π§ͺ Testing - Increase test coverage
- Fork repository and create feature branch
- Follow TypeScript/ESLint standards
- Add tests and update documentation
- Run
npm run lint && npm test && npm run build
- Submit pull request with clear description
π Complete Contributing Guide β
- π Documentation Hub - Complete documentation structure
- π Setup Guides - Step-by-step installation and setup
- π API Reference - Complete tool documentation
- ποΈ Architecture - System design and technical details
- π³ Docker Deployment - Container deployment guide
- π§ Troubleshooting - Common issues and solutions
- πΌ Business Workflows - Business process integration
- π§ͺ Examples - Code examples and usage patterns
- π Issues - Report bugs via GitHub Issues
- π¬ Discussions - Join community discussions
- π Documentation - Comprehensive guides available
This project is licensed under the MIT License.
Built with β€οΈ for the MCP ecosystem