gdrive

AojdevStudio/gdrive

3.2

If you are the rightful owner of gdrive and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to henry@mcphub.com.

A Model Context Protocol (MCP) server that provides comprehensive integration with Google Drive, Sheets, Docs, and Forms.

Tools
14
Resources
0
Prompts
0

Google Drive MCP Server

License: MIT TypeScript Docker Redis

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.

πŸš€ Quick Start

πŸ“‹ Prerequisites

You'll need a Google account and Node.js 18+ installed.

πŸ“–

⚑ Fast Track Setup

  1. 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

    πŸ“–

  2. 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
    

    πŸ“–

  3. Start Server

    node ./dist/index.js
    

🐳 Docker Setup (Recommended)

# 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

πŸ“–

🚨 Breaking Changes in v2.0.0

Major Version Update: Google Drive MCP Server v2.0.0 introduces significant architectural improvements that require migration from previous versions.

What Changed?

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"
  }
}

Why This Improves Your Experience

  • 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

Migration Required

πŸ“– - 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.


πŸ” Authentication

The server features automatic OAuth token refresh with enterprise-grade encryption - authenticate once, works forever.

⚑ Quick Authentication

# Local setup
export GDRIVE_TOKEN_ENCRYPTION_KEY=$(openssl rand -base64 32)
node ./dist/index.js auth

# Docker setup
./scripts/auth.sh

πŸ“–

πŸ”— Claude Desktop Integration

⚑ Quick Integration

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"]
    }
  }
}

πŸ“–

πŸš€ Key Features

πŸ” Enterprise-Grade Security

  • 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

πŸ“ Google Drive Operations

  • 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

πŸ“Š Google Sheets Integration

  • 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
Formula Automation Examples

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)"
});
Security Considerations for Formula Operations

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, or IMPORTHTML
  • 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');
}
Cell Formatting Examples

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
  }
});

πŸ“ Google Docs Manipulation

  • 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

πŸ“‹ Google Forms Builder

  • 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

πŸ”§ Google Apps Script Access

  • 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

⚑ Performance & Scalability

  • 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

πŸ—οΈ Architecture Overview

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

Core Components

  • 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

Operation-Based Tool Architecture (v2.0.0)

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.

πŸ“š API Reference

πŸ“– Available Tools (v2.0.0)

The server provides 5 consolidated operation-based tools with 32 total operations:

sheets - Google Sheets Operations (12 operations)

Unified tool for all Google Sheets functionality:

  • list - List all sheets in a spreadsheet
  • read - Read data from a specific range
  • create - Create a new sheet in a spreadsheet
  • rename - Rename an existing sheet
  • delete - Delete a sheet
  • update - Update cell values in a range
  • updateFormula - Apply formulas to cells
  • format - Apply formatting (bold, colors, number formats)
  • conditionalFormat - Add conditional formatting rules
  • append - Append rows to a sheet
  • freeze - Freeze header rows/columns
  • setColumnWidth - Adjust column widths
drive - Google Drive Operations (7 operations)

Unified tool for file and folder management:

  • search - Search files with natural language queries
  • enhancedSearch - Advanced search with filters
  • read - Read file contents
  • create - Create new files
  • update - Update existing files
  • createFolder - Create new folders
  • batch - Batch file operations
forms - Google Forms Operations (4 operations)

Unified tool for form creation and management:

  • create - Create new forms
  • get - Retrieve form details
  • addQuestion - Add questions to forms
  • listResponses - Get form responses
docs - Google Docs Operations (5 operations)

Unified tool for document manipulation:

  • create - Create new documents
  • insertText - Insert text at positions
  • replaceText - Find and replace text
  • applyTextStyle - Apply formatting (bold, italic, colors)
  • insertTable - Insert tables
batch - Batch File Operations (4 operations)

Unified tool for efficient multi-file processing:

  • create - Create multiple files
  • update - Update multiple files
  • delete - Delete multiple files
  • move - Move multiple files

πŸ“‚ Resources

  • MCP Resource Access: gdrive:///<file_id> URIs for file access

πŸ“–

πŸ”„ Migration from v1.x

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
listSheetssheets"list"
readSheetsheets"read"
createSheetsheets"create"
updateCellssheets"update"
...and 28 moreSee

πŸ“–

🎯 Key Capabilities Summary

  • 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

πŸ”’ Security Features

  • 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

πŸ“–

πŸ”‘ Key Rotation

πŸ”„ Initial Migration (Required for Existing Installations)

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

πŸ”„ Rotating Encryption 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

βš™οΈ Key Management Environment Variables

VariableDescriptionDefault
GDRIVE_TOKEN_ENCRYPTION_KEYBase64-encoded 32-byte encryption keyAuto-generated
GDRIVE_KEY_DERIVATION_ITERATIONSPBKDF2 iterations for key strengthening100000
GDRIVE_ROTATION_BACKUP_COUNTNumber of backup files to retain5

πŸ› οΈ CLI Commands

# 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

🚨 Troubleshooting Key Issues

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

πŸ“–

πŸ₯ Health Monitoring

# Check health status
node ./dist/index.js health

Health States: 🟒 HEALTHY | 🟑 DEGRADED | πŸ”΄ UNHEALTHY

πŸ“–

πŸ’‘ Usage Examples

πŸ” Quick Examples (v2.0.0)

// 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]]
});

πŸ“–

πŸ›‘οΈ Security Features

πŸ” Enterprise-Grade Protection

  • 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

πŸ“–

βš™οΈ Configuration

πŸ“ Key Environment Variables

VariableDescriptionRequired
GDRIVE_TOKEN_ENCRYPTION_KEY32-byte base64 encryption keyβœ…
GDRIVE_KEY_DERIVATION_ITERATIONSPBKDF2 iterations for key strengthening (min: 100000)❌
GDRIVE_ROTATION_BACKUP_COUNTNumber of backup files to retain during rotation❌
REDIS_URLRedis cache connection URL❌
LOG_LEVELWinston logging level (info/debug)❌

πŸ“‹ Sample .env File

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

πŸ“–

πŸ”§ Troubleshooting

🚨 Quick Fixes

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 and logs/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

πŸ“–

πŸ› οΈ Development

πŸ”§ Development Setup

# 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

πŸ“¦ Available Commands

  • npm run build - Compile TypeScript
  • npm run watch - Auto-rebuild on changes
  • npm test - Run test suite
  • npm run lint - Code quality checks

πŸ“–

🀝 Contributing

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

πŸ“‹ Quick Process

  1. Fork repository and create feature branch
  2. Follow TypeScript/ESLint standards
  3. Add tests and update documentation
  4. Run npm run lint && npm test && npm run build
  5. Submit pull request with clear description

πŸ“–

πŸ“š Complete Documentation

πŸ“– Documentation Index

  • - Complete documentation structure
  • - Step-by-step installation and setup
  • - Complete tool documentation
  • - System design and technical details
  • - Container deployment guide
  • - Common issues and solutions
  • - Business process integration
  • - Code examples and usage patterns

πŸ“ž Support

  • πŸ› Issues - Report bugs via GitHub Issues
  • πŸ’¬ Discussions - Join community discussions
  • πŸ“– Documentation - Comprehensive guides available

πŸ“„ License

This project is licensed under the MIT License.


Built with ❀️ for the MCP ecosystem

⭐ Star this repo | πŸ› Report Bug | πŸ’‘ Request Feature