EXAMPLES.md•14.4 kB
# Usage Examples
This document provides comprehensive examples of how to use the Google Drive MCP Server with various MCP clients and scenarios.
## Table of Contents
1. [MCP Client Integration](#mcp-client-integration)
2. [Tool Usage Examples](#tool-usage-examples)
3. [Common Workflows](#common-workflows)
4. [Advanced Use Cases](#advanced-use-cases)
5. [CLI Examples](#cli-examples)
## MCP Client Integration
### Claude Desktop Configuration
Add the Google Drive MCP Server to your Claude Desktop configuration:
**macOS/Linux**: `~/.config/claude/claude_desktop_config.json`
**Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
```json
{
"mcpServers": {
"google-drive": {
"command": "node",
"args": ["/path/to/google-drive-mcp-server/dist/index.js"],
"env": {
"GOOGLE_CLIENT_ID": "your-client-id.googleusercontent.com",
"GOOGLE_CLIENT_SECRET": "your-client-secret",
"CACHE_DIR": "/path/to/cache",
"LOG_LEVEL": "info"
}
}
}
}
```
### Generic MCP Client Configuration
For other MCP-compatible clients:
```javascript
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
const transport = new StdioClientTransport({
command: 'node',
args: ['/path/to/google-drive-mcp-server/dist/index.js'],
env: {
GOOGLE_CLIENT_ID: 'your-client-id',
GOOGLE_CLIENT_SECRET: 'your-client-secret'
}
});
const client = new Client({
name: "google-drive-client",
version: "1.0.0"
}, {
capabilities: {}
});
await client.connect(transport);
```
## Tool Usage Examples
### 1. drive_search_files
Search for files on Google Drive with various filters.
**Basic Search:**
```json
{
"name": "drive_search_files",
"arguments": {
"query": "presentation"
}
}
```
**Advanced Search with Filters:**
```json
{
"name": "drive_search_files",
"arguments": {
"query": "quarterly report",
"fileType": ["application/pdf", "application/vnd.google-apps.document"],
"modifiedAfter": "2024-01-01",
"folderId": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
"limit": 10
}
}
```
**Search in Specific Folder:**
```json
{
"name": "drive_search_files",
"arguments": {
"query": "*",
"folderId": "your-folder-id",
"orderBy": "modifiedTime"
}
}
```
### 2. drive_get_file
Retrieve complete file information and content.
**Get File with Full Content:**
```json
{
"name": "drive_get_file",
"arguments": {
"fileId": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
"includeContent": true
}
}
```
**Get File Metadata Only:**
```json
{
"name": "drive_get_file",
"arguments": {
"fileId": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
"includeContent": false
}
}
```
### 3. drive_get_content_chunk
Extract specific portions of file content.
**Get Content by Page Range:**
```json
{
"name": "drive_get_content_chunk",
"arguments": {
"fileId": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
"startPage": 1,
"endPage": 3
}
}
```
**Get Content by Character Range:**
```json
{
"name": "drive_get_content_chunk",
"arguments": {
"fileId": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
"startChar": 0,
"endChar": 5000
}
}
```
**Search for Specific Content:**
```json
{
"name": "drive_get_content_chunk",
"arguments": {
"fileId": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
"searchQuery": "budget analysis",
"contextLines": 3
}
}
```
### 4. drive_get_file_metadata
Get detailed metadata and permissions.
**Basic Metadata:**
```json
{
"name": "drive_get_file_metadata",
"arguments": {
"fileId": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms"
}
}
```
**Metadata with Permissions:**
```json
{
"name": "drive_get_file_metadata",
"arguments": {
"fileId": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
"includePermissions": true
}
}
```
### 5. drive_list_folder
List contents of a folder.
**List Folder Contents:**
```json
{
"name": "drive_list_folder",
"arguments": {
"folderId": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms"
}
}
```
**List with Filters:**
```json
{
"name": "drive_list_folder",
"arguments": {
"folderId": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
"fileType": ["application/pdf"],
"orderBy": "name",
"limit": 20
}
}
```
### 6. drive_get_comments
Get comments from a file (if available).
**Get All Comments:**
```json
{
"name": "drive_get_comments",
"arguments": {
"fileId": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms"
}
}
```
**Get Recent Comments:**
```json
{
"name": "drive_get_comments",
"arguments": {
"fileId": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
"limit": 10,
"includeReplies": true
}
}
```
## Common Workflows
### Workflow 1: Research Document Analysis
**Step 1: Search for relevant documents**
```json
{
"name": "drive_search_files",
"arguments": {
"query": "market research 2024",
"fileType": ["application/pdf", "application/vnd.google-apps.document"],
"modifiedAfter": "2024-01-01"
}
}
```
**Step 2: Get metadata to understand document structure**
```json
{
"name": "drive_get_file_metadata",
"arguments": {
"fileId": "found-document-id"
}
}
```
**Step 3: Extract specific sections**
```json
{
"name": "drive_get_content_chunk",
"arguments": {
"fileId": "found-document-id",
"searchQuery": "executive summary",
"contextLines": 5
}
}
```
### Workflow 2: Large Document Processing
**Step 1: Check document size**
```json
{
"name": "drive_get_file_metadata",
"arguments": {
"fileId": "large-document-id"
}
}
```
**Step 2: Process in chunks**
```json
{
"name": "drive_get_content_chunk",
"arguments": {
"fileId": "large-document-id",
"startPage": 1,
"endPage": 10
}
}
```
**Step 3: Continue with next chunk**
```json
{
"name": "drive_get_content_chunk",
"arguments": {
"fileId": "large-document-id",
"startPage": 11,
"endPage": 20
}
}
```
### Workflow 3: Folder Content Analysis
**Step 1: List folder contents**
```json
{
"name": "drive_list_folder",
"arguments": {
"folderId": "project-folder-id",
"orderBy": "modifiedTime"
}
}
```
**Step 2: Process each relevant file**
```json
{
"name": "drive_get_file",
"arguments": {
"fileId": "file-from-folder",
"includeContent": true
}
}
```
## Advanced Use Cases
### Use Case 1: Content Summarization Pipeline
```javascript
// Example client code for content summarization
async function summarizeDocument(fileId) {
// Get document metadata
const metadata = await client.callTool('drive_get_file_metadata', {
fileId: fileId
});
// If document is large, process in chunks
if (metadata.size > 100000) {
const chunks = [];
const totalPages = metadata.pageCount || 10;
for (let page = 1; page <= totalPages; page += 5) {
const chunk = await client.callTool('drive_get_content_chunk', {
fileId: fileId,
startPage: page,
endPage: Math.min(page + 4, totalPages)
});
chunks.push(chunk.content);
}
return chunks;
} else {
// Process entire document
const file = await client.callTool('drive_get_file', {
fileId: fileId,
includeContent: true
});
return [file.content];
}
}
```
### Use Case 2: Multi-Document Research
```javascript
async function researchTopic(topic, dateRange) {
// Search for relevant documents
const searchResults = await client.callTool('drive_search_files', {
query: topic,
modifiedAfter: dateRange.start,
modifiedBefore: dateRange.end,
limit: 20
});
const insights = [];
for (const file of searchResults.files) {
// Get key sections from each document
const relevantContent = await client.callTool('drive_get_content_chunk', {
fileId: file.id,
searchQuery: topic,
contextLines: 3
});
insights.push({
source: file.name,
content: relevantContent.matches,
metadata: {
modifiedTime: file.modifiedTime,
owner: file.owners[0]?.displayName
}
});
}
return insights;
}
```
### Use Case 3: Document Version Comparison
```javascript
async function compareDocumentVersions(folderId, documentName) {
// Find all versions of a document
const files = await client.callTool('drive_list_folder', {
folderId: folderId
});
const versions = files.files
.filter(f => f.name.includes(documentName))
.sort((a, b) => new Date(b.modifiedTime) - new Date(a.modifiedTime));
const comparisons = [];
for (let i = 0; i < Math.min(versions.length, 3); i++) {
const content = await client.callTool('drive_get_file', {
fileId: versions[i].id,
includeContent: true
});
comparisons.push({
version: i + 1,
modifiedTime: versions[i].modifiedTime,
content: content.content,
wordCount: content.metadata.wordCount
});
}
return comparisons;
}
```
## CLI Examples
### Basic CLI Usage
```bash
# Search for files
npx google-drive-mcp search --query "budget report" --type pdf
# Get file information
npx google-drive-mcp info --file-id "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms"
# Extract content chunk
npx google-drive-mcp content --file-id "file-id" --start-page 1 --end-page 5
# List folder contents
npx google-drive-mcp list --folder-id "folder-id" --type document
```
### Advanced CLI Usage
```bash
# Search with date filters
npx google-drive-mcp search \
--query "quarterly report" \
--modified-after "2024-01-01" \
--modified-before "2024-12-31" \
--limit 10
# Extract content with keyword search
npx google-drive-mcp content \
--file-id "file-id" \
--search "executive summary" \
--context-lines 3
# Get file with specific format
npx google-drive-mcp get \
--file-id "file-id" \
--format markdown \
--output summary.md
# Batch process folder
npx google-drive-mcp batch \
--folder-id "folder-id" \
--action extract \
--output-dir ./extracted/
```
### Automation Scripts
**Bash Script for Daily Report Processing:**
```bash
#!/bin/bash
# Daily report processing script
DATE=$(date +%Y-%m-%d)
REPORT_FOLDER="1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms"
echo "Processing daily reports for $DATE"
# Search for today's reports
npx google-drive-mcp search \
--query "daily report" \
--folder-id "$REPORT_FOLDER" \
--modified-after "$DATE" \
--format json > reports.json
# Process each report
cat reports.json | jq -r '.files[].id' | while read file_id; do
echo "Processing file: $file_id"
# Extract summary section
npx google-drive-mcp content \
--file-id "$file_id" \
--search "summary" \
--context-lines 5 \
--output "summary_${file_id}.md"
done
echo "Processing complete"
```
**Python Script for Content Analysis:**
```python
#!/usr/bin/env python3
import subprocess
import json
import sys
def search_and_analyze(query, file_type="pdf"):
"""Search for files and analyze their content"""
# Search for files
search_cmd = [
"npx", "google-drive-mcp", "search",
"--query", query,
"--type", file_type,
"--format", "json"
]
result = subprocess.run(search_cmd, capture_output=True, text=True)
files = json.loads(result.stdout)
analysis_results = []
for file_info in files.get('files', []):
file_id = file_info['id']
# Get file content
content_cmd = [
"npx", "google-drive-mcp", "content",
"--file-id", file_id,
"--format", "json"
]
content_result = subprocess.run(content_cmd, capture_output=True, text=True)
content_data = json.loads(content_result.stdout)
analysis_results.append({
'file': file_info,
'content': content_data,
'word_count': len(content_data.get('content', '').split())
})
return analysis_results
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python analyze.py <search_query>")
sys.exit(1)
query = sys.argv[1]
results = search_and_analyze(query)
print(f"Found {len(results)} files matching '{query}'")
for result in results:
print(f"- {result['file']['name']}: {result['word_count']} words")
```
## Error Handling Examples
### Handling Authentication Errors
```javascript
try {
const result = await client.callTool('drive_search_files', {
query: 'test'
});
} catch (error) {
if (error.code === 'AUTHENTICATION_FAILED') {
console.log('Please re-authenticate with Google Drive');
// Trigger re-authentication flow
} else if (error.code === 'QUOTA_EXCEEDED') {
console.log('API quota exceeded, please try again later');
// Implement retry with backoff
} else {
console.error('Unexpected error:', error.message);
}
}
```
### Handling Large File Processing
```javascript
async function processLargeFile(fileId) {
try {
// First check file size
const metadata = await client.callTool('drive_get_file_metadata', {
fileId: fileId
});
if (metadata.size > 50 * 1024 * 1024) { // 50MB
console.log('File is large, processing in chunks...');
// Process in smaller chunks
const chunks = [];
const chunkSize = 10000; // characters
let startChar = 0;
while (startChar < metadata.size) {
const chunk = await client.callTool('drive_get_content_chunk', {
fileId: fileId,
startChar: startChar,
endChar: startChar + chunkSize
});
chunks.push(chunk.content);
startChar += chunkSize;
// Add delay to avoid rate limiting
await new Promise(resolve => setTimeout(resolve, 100));
}
return chunks.join('\n');
} else {
// Process entire file
const file = await client.callTool('drive_get_file', {
fileId: fileId,
includeContent: true
});
return file.content;
}
} catch (error) {
console.error('Error processing file:', error.message);
throw error;
}
}
```
These examples demonstrate the flexibility and power of the Google Drive MCP Server across different use cases and integration scenarios.