### Install Server Dependencies Source: https://github.com/a-bonus/google-docs-mcp/blob/main/docs/index.html Install the required Node.js packages for the server using npm. Ensure you are in the server's root directory. ```bash npm install ``` -------------------------------- ### Insert Table with Data Example Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/02-tools-google-docs.md Example of using insertTableWithData to create a table with initial data. ```javascript await insertTableWithData({ documentId: '1-5XzW3YN8_Q1X2Y3Z', index: 100, data: [ ['Name', 'Score', 'Grade'], ['Alice', '95', 'A'], ['Bob', '87', 'B'] ] }); ``` -------------------------------- ### Clone and Build Project Source: https://github.com/a-bonus/google-docs-mcp/blob/main/CONTRIBUTING.md Clone the repository, navigate to the project directory, install dependencies, and build the project. ```bash git clone https://github.com/a-bonus/google-docs-mcp.git cd google-docs-mcp npm install npm run build ``` -------------------------------- ### Google Drive Operations Source: https://github.com/a-bonus/google-docs-mcp/blob/main/README.md Examples for listing, searching, and managing files and folders in Google Drive. ```text "List my 10 most recent Google Docs" ``` ```text "Search for documents containing 'project proposal'" ``` ```text "Create a folder called 'Meeting Notes' and move document ABC123 into it" ``` -------------------------------- ### Replace Table Row Data Example Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/02-tools-google-docs.md Example demonstrating how to replace multiple rows in a table with new data. ```javascript await replaceTableRowData({ documentId: '1-5XzW3YN8_Q1X2Y3Z', tableId: 'table1', startRowIndex: 1, data: [ ['Updated', 'Row', 'One'], ['Updated', 'Row', 'Two'] ] }); ``` -------------------------------- ### Example Google Docs Editing Prompts Source: https://github.com/a-bonus/google-docs-mcp/blob/main/vscode.md Apply formatting and content modifications to your Google Docs using these prompts. Examples include adding headings, applying styles, and inserting tables. ```plaintext "Add a heading 'Summary' to the beginning of document ID: 1JKL..." "Format all text containing 'important' as bold in my document" "Insert a table with 3 columns and 5 rows at the end of the document" "Apply paragraph formatting to make all headings centered" ``` -------------------------------- ### Local Development Configuration (stdio) Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/07-configuration.md Sets up environment variables for local development using the stdio transport. Includes client ID, secret, tool groups, and commands for authorization and starting the server. ```bash #!/bin/bash export GOOGLE_CLIENT_ID="123456789-abcdef.apps.googleusercontent.com" export GOOGLE_CLIENT_SECRET="GOCSPX-xyz123" export MCP_TOOL_GROUPS="docs,sheets,drive" # First time: authorize npx @a-bonus/google-docs-mcp auth # Then: start server npx @a-bonus/google-docs-mcp ``` -------------------------------- ### Error Handling Example Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/INDEX.md Demonstrates how to handle potential errors when interacting with Google APIs, such as 'not found' or authorization failures. ```javascript try { const doc = await readDocument({ documentId: 'invalid-id' }); } catch (error) { console.error(`Failed: ${error.message}`); if (error.message.includes('not found')) { // Handle missing document } else if (error.message.includes('authorization')) { // Handle auth failure } } ``` -------------------------------- ### Example Workflow for Creating a Formatted Report Source: https://github.com/a-bonus/google-docs-mcp/blob/main/vscode.md Follow this multi-step workflow to create a new Google Doc, add a title, insert a table, and add section headings using MCP prompts. ```plaintext 1. "Create a new document called 'Monthly Report' in my Reports folder" 2. "Add the title 'Monthly Performance Report' as a centered Heading 1" 3. "Insert a table with 4 columns and 6 rows for the data" 4. "Add section headings for Executive Summary, Key Metrics, and Action Items" ``` -------------------------------- ### Google Calendar Operations Source: https://github.com/a-bonus/google-docs-mcp/blob/main/README.md Examples for managing calendar events, including creating, rescheduling, and deleting. ```text "What's on my calendar this week?" ``` ```text "Create an event titled 'Project review' tomorrow from 2pm to 3pm Pacific time" ``` ```text "Quick add: lunch with Alex Friday 12:30" ``` ```text "Reschedule event abc123 to next Monday at 10am" ``` ```text "Delete the 'Standup' event tomorrow" ``` ```text "List all events on my calendar between April 15 and April 22" ``` ```text "Schedule a 30-minute meeting with bob@example.com next Wednesday at 11am with a Google Meet link" ``` -------------------------------- ### Gmail Operations Source: https://github.com/a-bonus/google-docs-mcp/blob/main/README.md Examples for managing emails, including searching, reading, sending, and organizing. ```text "Show me my 20 most recent unread emails" ``` ```text "Search Gmail for messages from alice@example.com in the last 7 days" ``` ```text "Read the full body of message ID 18c3f4a2b1d9" ``` ```text "Send an email to bob@example.com with the subject 'Weekly update' and this body..." ``` ```text "Reply to message 18c3f4a2b1d9 with 'Thanks, confirmed.'" ``` ```text "Star message 18c3f4a2b1d9 and archive it" ``` ```text "Move message 18c3f4a2b1d9 to Trash" ``` ```text "List all my Gmail labels" ``` ```text "Draft a reply to that email but don't send it yet — let me review first" ``` ```text "Show me my drafts, then send the one to bob@" ``` ```text "Triage my unread inbox: tell me which 20 emails need attention and which are noise" ``` -------------------------------- ### Deploy Google Docs MCP to Cloud Run Source: https://github.com/a-bonus/google-docs-mcp/blob/main/README.md Deploys the service from source to Cloud Run, setting essential environment variables for remote mode, OAuth, and persistent token storage. The example uses '|' as a delimiter for environment variables due to commas in ALLOWED_DOMAINS. ```bash gcloud run deploy google-docs-mcp \ --source . \ --region europe-west3 \ --port 8080 \ --allow-unauthenticated \ --set-env-vars "^|^MCP_TRANSPORT=httpStream|BASE_URL=https://your-service.run.app|ALLOWED_DOMAINS=yourdomain.com|GOOGLE_CLIENT_ID=...|GOOGLE_CLIENT_SECRET=...|TOKEN_STORE=firestore|JWT_SIGNING_KEY=your-secret-key" ``` -------------------------------- ### Example Google Drive File Management Prompts Source: https://github.com/a-bonus/google-docs-mcp/blob/main/vscode.md Interact with your Google Drive files and folders using these prompts in VS Code. Operations include viewing contents, creating folders, moving, and copying files. ```plaintext "Show me the contents of my root Drive folder" "Create a folder called 'Project X' in folder ID: 1DEF..." "Move document ID: 1GHI... to the Project X folder" "Copy my template document and rename it to 'New Report'" ``` -------------------------------- ### Configure Cloud Run Minimum Instances Source: https://github.com/a-bonus/google-docs-mcp/blob/main/README.md Set the minimum number of instances for a Cloud Run service to keep it warm and prevent cold start issues during OAuth sign-in. This incurs a small monthly cost. ```bash gcloud run services update --region --min-instances=1 ``` -------------------------------- ### Example Google Docs Operations Prompts Source: https://github.com/a-bonus/google-docs-mcp/blob/main/vscode.md Use these natural language prompts within VS Code to perform various operations on your Google Docs, such as listing, reading, creating, and searching documents. ```plaintext "List my recent Google Docs from the last 7 days" "Read the content of document ID: 1ABC..." "Create a new document called 'Project Notes' in my Work folder" "Search for documents containing 'meeting notes'" ``` -------------------------------- ### Configure MCP Client for Google Docs Source: https://github.com/a-bonus/google-docs-mcp/blob/main/README.md Add this configuration to your MCP client (Claude Desktop, Cursor, Windsurf) to integrate with the Google Docs MCP Server. Ensure your client starts the server automatically when needed. ```json { "mcpServers": { "google-docs": { "command": "npx", "args": ["-y", "@a-bonus/google-docs-mcp"], "env": { "GOOGLE_CLIENT_ID": "your-client-id", "GOOGLE_CLIENT_SECRET": "your-client-secret" } } } } ``` -------------------------------- ### Google Sheets Operations Source: https://github.com/a-bonus/google-docs-mcp/blob/main/README.md Examples for reading, writing, formatting, and managing data within Google Sheets. ```text "Read range A1:D10 from spreadsheet XYZ789" ``` ```text "Write [[Name, Score], [Alice, 95], [Bob, 87]] to range A1 in spreadsheet XYZ789" ``` ```text "Create a new spreadsheet titled 'Q1 Report'" ``` ```text "Format row 1 as bold with a light blue background in spreadsheet XYZ789" ``` ```text "Freeze the first row in spreadsheet XYZ789" ``` ```text "Add a dropdown with options [Open, In Progress, Done] to range C2:C100" ``` ```text "Create a table named 'Tasks' in range A1:D10 with columns: Task (TEXT), Status (DROPDOWN: 'Not Started','In Progress','Done'), Priority (NUMBER)" ``` ```text "Add a medium solid border around A1:D10 in spreadsheet XYZ789" ``` ```text "Protect the header row so collaborators can't accidentally edit it" ``` ```text "Auto-fit row heights for rows 2–50 after wrapping text" ``` -------------------------------- ### Basic Markdown Document Example Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/05-tools-utilities.md Illustrates a basic markdown structure including headings, text formatting, links, lists, blockquotes, and code blocks. This serves as a reference for markdown syntax supported by the transformer. ```markdown # Main Title ## Section One This is regular text with **bold** and *italic*. Here's a [link to example.com](https://example.com). ### Subsection - Bullet point 1 - Bullet point 2 - Bullet point 3 1. Numbered item 1 2. Numbered item 2 --- ## Section Two > This is a block quote. > It can span multiple lines. ### Code Example ``` def hello(): print("Hello, World!") ``` ``` -------------------------------- ### Google API Types Import Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/06-types.md Example import statement for Google API types from the 'googleapis' package, covering common services like Docs, Drive, Sheets, Gmail, and Calendar. ```typescript import { docs_v1, drive_v3, sheets_v4, gmail_v1, calendar_v3 } from 'googleapis' ``` -------------------------------- ### Create Project Folder Source: https://github.com/a-bonus/google-docs-mcp/blob/main/SAMPLE_TASKS.md Use createFolder to establish a main project directory. This is the first step in setting up a complete project structure. ```python folder_id = createFolder('My Project') ``` -------------------------------- ### Navigate into Server Directory Source: https://github.com/a-bonus/google-docs-mcp/blob/main/docs/index.html Change your current directory to the newly cloned server repository. This is necessary for subsequent commands. ```bash cd mcp-googledocs-server ``` -------------------------------- ### Input Validation Error Example Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/08-errors.md An example of a Zod validation error message, indicating that the 'endIndex' must be greater than the 'startIndex'. This is common for range-based operations. ```text Zod validation error: "endIndex must be greater than startIndex" ``` -------------------------------- ### Service Account Configuration (Local) Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/07-configuration.md Sets up local execution using a service account for authentication. Requires specifying the path to the service account key file and the user to impersonate. ```bash #!/bin/bash export SERVICE_ACCOUNT_PATH="/secure/service-account-key.json" export GOOGLE_IMPERSONATE_USER="automation@company.com" npx @a-bonus/google-docs-mcp ``` -------------------------------- ### Replace Table Row Data Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/02-tools-google-docs.md Replaces the content of one or more rows in a table starting from a specified row index. Requires document ID, table ID, start row index, and the new data. ```typescript async function replaceTableRowData(args: { documentId: string tableId: string startRowIndex: number data: string[][] tabId?: string }): Promise ``` -------------------------------- ### Project Architecture Entry Points Source: https://github.com/a-bonus/google-docs-mcp/blob/main/CONTRIBUTING.md Overview of the main entry points for the project, including the CLI, MCP server startup, authentication module, and Google API client singletons. ```plaintext src/index.ts Entry point: CLI (auth subcommand) and MCP server startup src/auth.ts OAuth / service account authentication src/clients.ts Google API client singletons (Docs, Drive, Sheets) ``` -------------------------------- ### Run the Compiled Server Source: https://github.com/a-bonus/google-docs-mcp/blob/main/docs/index.html Execute the compiled server JavaScript file using Node.js. This initiates the Google authorization flow. ```bash node ./dist/server.js ``` -------------------------------- ### Get Folder Metadata Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/04-tools-google-drive-gmail-calendar.md Retrieves metadata for a specific Google Drive folder using its ID. ```typescript async function getFolderInfo(args: { folderId: string }): Promise ``` -------------------------------- ### Register Local Build with MCP Client Source: https://github.com/a-bonus/google-docs-mcp/blob/main/CONTRIBUTING.md Configure the MCP client to point to the local build by specifying the command and arguments to run the Google Docs server. ```json { "mcpServers": { "google-docs": { "command": "node", "args": ["/absolute/path/to/mcp-googledocs-server/dist/index.js"] } } } ``` -------------------------------- ### Create Project Index Document Source: https://github.com/a-bonus/google-docs-mcp/blob/main/SAMPLE_TASKS.md Generate a project index document that lists all resources. This provides a central reference point for all project-related files. ```python createDocument('Project Index', content=index_content) ``` -------------------------------- ### Run Live Docs Verification Test Source: https://github.com/a-bonus/google-docs-mcp/blob/main/README.md Command to execute the live integration test for cloneTable against the Google Docs API. ```bash GOOGLE_DOCS_LIVE_TESTS=1 npm run test:live:docs ``` -------------------------------- ### Delete Table Rows Source: https://github.com/a-bonus/google-docs-mcp/blob/main/docs/planning-doc-formatting-spec.md Removes a specified number of rows from a table, starting at a given row index. ```typescript { documentId: string; tabId?: string; tableId: string; rowStart: number; rowCount: number; } ``` -------------------------------- ### Create Document Template Source: https://github.com/a-bonus/google-docs-mcp/blob/main/SAMPLE_TASKS.md Set up template documents with placeholder text. These templates are used to generate standardized reports. ```python createDocument('Report Template', content='Date: {{DATE}}\nName: {{NAME}}') ``` -------------------------------- ### Get Table Structure Source: https://github.com/a-bonus/google-docs-mcp/blob/main/src/tools/docs/README.md Retrieves the row, column, and cell structure for a specified table in a Google Document. ```typescript getTableStructure ``` -------------------------------- ### Clone the Google Docs MCP Repository Source: https://github.com/a-bonus/google-docs-mcp/blob/main/docs/index.html Clone the server repository from GitHub to your local machine. This command initializes the project directory. ```bash git clone https://github.com/a-bonus/google-docs-mcp.git mcp-googledocs-server ``` -------------------------------- ### List Gmail Messages Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/INDEX.md Lists Gmail messages, with support for filtering using a query. For example, to list unread messages. ```javascript const messages = await listMessages({ q: 'is:unread' }); ``` -------------------------------- ### Get Table Structure Details Source: https://github.com/a-bonus/google-docs-mcp/blob/main/docs/planning-doc-formatting-spec.md Fetches the detailed cell map for a specific table within a document, identified by its tableId. ```typescript { documentId: string; tabId?: string; tableId: string; } ``` -------------------------------- ### Get Specific Comment from Google Sheet Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/03-tools-google-sheets.md Fetches the full content and replies for a specific comment in a Google Sheet using its ID. ```typescript async function getSheetsComment(args: { spreadsheetId: string commentId: string }): Promise ``` -------------------------------- ### Format Code with Prettier Source: https://github.com/a-bonus/google-docs-mcp/blob/main/CONTRIBUTING.md Run this command to format your code according to the project's Prettier configuration. ```bash npm run format ``` -------------------------------- ### Define RangeParameters Schema Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/06-types.md Schema for character-level index ranges (1-based, inclusive start, exclusive end). Ensures endIndex is greater than startIndex. ```typescript export const RangeParameters = z .object({ startIndex: z .number() .int() .min(1) .describe('The starting index of the text range (inclusive, starts from 1).'), endIndex: z.number().int().min(1).describe('The ending index of the text range (exclusive).'), }) .refine((data) => data.endIndex > data.startIndex, { message: 'endIndex must be greater than startIndex', path: ['endIndex'], }); ``` ```typescript type RangeParameters = { startIndex: number // 1-based, inclusive endIndex: number // 1-based, exclusive (must be > startIndex) } ``` -------------------------------- ### Configure MCP Tool Groups Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/07-configuration.md Select specific tool groups to register with the server. This can reduce startup time and memory usage by disabling unused tools. Defaults to all groups. ```bash # Register only Docs and Sheets export MCP_TOOL_GROUPS="docs,sheets" npx @a-bonus/google-docs-mcp ``` ```bash # Register all groups (explicit) export MCP_TOOL_GROUPS="all" npx @a-bonus/google-docs-mcp ``` ```bash # Register Sheets and Gmail, skip others export MCP_TOOL_GROUPS="sheets,gmail" npx @a-bonus/google-docs-mcp ``` -------------------------------- ### Create Google Calendar Event Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/INDEX.md Creates a new event in Google Calendar. Requires title, start time, and optionally end time. ```javascript await createEvent({ title: '...', startTime: '2024-06-15T14:00:00Z' }); ``` -------------------------------- ### Get Conditional Formatting Rules Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/03-tools-google-sheets.md Lists all conditional formatting rules for a given spreadsheet or sheet. Useful for auditing or retrieving existing configurations. ```typescript async function getConditionalFormatting(args: { spreadsheetId: string sheetId?: number }): Promise ``` -------------------------------- ### Multiple Profiles Configuration (Local) Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/07-configuration.md Configures and authorizes multiple Google accounts for local use by setting the GOOGLE_MCP_PROFILE environment variable. Allows switching between 'work' and 'personal' profiles for authentication and server startup. ```bash #!/bin/bash # Work account export GOOGLE_CLIENT_ID="work-id.apps.googleusercontent.com" export GOOGLE_CLIENT_SECRET="work-secret" export GOOGLE_MCP_PROFILE="work" npx @a-bonus/google-docs-mcp auth # Personal account export GOOGLE_CLIENT_ID="personal-id.apps.googleusercontent.com" export GOOGLE_CLIENT_SECRET="personal-secret" export GOOGLE_MCP_PROFILE="personal" npx @a-bonus/google-docs-mcp auth # Start with work profile export GOOGLE_MCP_PROFILE="work" npx @a-bonus/google-docs-mcp ``` -------------------------------- ### Verify Spreadsheet ID from URL Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/08-errors.md Example of how to extract a Google Spreadsheet ID from its URL. This is useful for verifying IDs when encountering 'Not Found' errors. ```text https://docs.google.com/spreadsheets/d/{ID}/edit ``` -------------------------------- ### quickAddEvent Source: https://github.com/a-bonus/google-docs-mcp/blob/main/src/tools/calendar/README.md Creates an event using natural language processing. Pass a string like "Lunch with Sarah tomorrow 12pm", and Google Calendar will parse the details. ```APIDOC ## quickAddEvent ### Description Natural-language event creation: pass "Lunch with Sarah tomorrow 12pm" and Google parses the rest. ### Parameters #### Request Body - **text** (string) - Required - The natural language text describing the event. - **calendarId** (string) - Optional - The ID of the calendar to add the event to. Defaults to "primary". ``` -------------------------------- ### Verify Document ID from URL Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/08-errors.md Example of how to extract a Google Document ID from its URL. This is useful for verifying IDs when encountering 'Not Found' errors. ```text https://docs.google.com/document/d/{ID}/edit ``` -------------------------------- ### Get Table Details Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/03-tools-google-sheets.md Retrieves detailed metadata for a specific table using its name or ID. Includes full definition, columns, and data range. ```typescript async function getTable(args: { spreadsheetId: string tableNameOrId: string }): Promise ``` -------------------------------- ### Registering a New Tool Source: https://github.com/a-bonus/google-docs-mcp/blob/main/src/tools/README.md To add a new tool, create a file in the domain folder, export a register function, and import it into the domain's index.ts. ```typescript export function register(server: FastMCP) { server.addTool({...}); } ``` -------------------------------- ### Get Specific Comment with Replies Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/02-tools-google-docs.md Fetches a single comment and its associated replies using the document and comment IDs. An optional tab ID can be provided. ```typescript async function getComment(args: { documentId: string commentId: string tabId?: string }): Promise ``` -------------------------------- ### wrapServerForRemote Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/01-overview.md Wraps a FastMCP server to enforce authentication, manage per-request Google API clients, and apply domain restrictions in remote deployment mode. ```APIDOC ## wrapServerForRemote ### Description Wraps a FastMCP server for remote deployment, enabling per-request authentication, client provisioning, and domain restrictions. ### Method `function wrapServerForRemote(server: FastMCP): void` ### Parameters #### Path Parameters - **server** (FastMCP) - Required - The FastMCP server instance to wrap. ### Request Example ```typescript import FastMCP from 'fastmcp'; import { wrapServerForRemote } from './remoteWrapper'; const server = new FastMCP(); // ... register tools ... wrapServerForRemote(server); ``` ### Response This function does not return a value; it modifies the server instance in place. ``` -------------------------------- ### Triage Calendar Conflicts for the Week Source: https://github.com/a-bonus/google-docs-mcp/blob/main/SAMPLE_TASKS.md Identifies and flags double-bookings on the calendar for the current week. It sorts events by start time and detects overlaps, suggesting resolutions. ```pseudocode Task: "Show me everything on my calendar this week and flag any double-bookings." Steps: 1. Call listEvents with timeMin=Monday 00:00 and timeMax=Sunday 23:59 in the user's timezone 2. Sort events by start time 3. Walk the sorted list and detect overlaps (event[i].end > event[i+1].start) 4. For each overlap, surface the two conflicting events with their summaries and times 5. Optionally suggest deleteEvent or updateEvent calls to resolve each conflict ``` -------------------------------- ### Get Document Metadata Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/04-tools-google-drive-gmail-calendar.md Retrieves metadata for a specific Google Document using its ID. Includes details like title, size, modification time, owner, and permissions. ```typescript async function getDocumentInfo(args: { documentId: string }): Promise ``` -------------------------------- ### Create Formatted Comparison Table Source: https://github.com/a-bonus/google-docs-mcp/blob/main/SAMPLE_TASKS.md Inserts a table, adds a header row, populates feature rows, applies alternating row background colors, formats the header, and aligns numeric columns. ```text Task: "Create a formatted comparison table of product features." Steps: 1. Insert a table with insertTable (5 rows x 4 columns) 2. Add header row with product names 3. Add feature rows with consistent formatting 4. Apply alternating row background colors for readability 5. Format the header row with bold text and background color 6. Align numeric columns to the right ``` -------------------------------- ### Configure Claude Desktop MCP Server Source: https://github.com/a-bonus/google-docs-mcp/blob/main/docs/index.html Add or modify the 'mcpServers' section in Claude's configuration file to include the Google Docs MCP server. Replace the placeholder path with your repository's absolute path. ```json { "mcpServers": { "google-docs-mcp": { "command": "node", "args": [ "/PAT ``` -------------------------------- ### Get Google Sheet Metadata Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/03-tools-google-sheets.md Retrieves metadata for a Google Sheet, including its title, locale, and a list of all sheets within it. Each sheet's metadata includes its ID, title, index, and dimensions. ```typescript async function getSpreadsheetInfo(args: { spreadsheetId: string }): Promise ``` -------------------------------- ### Format Document with Multi-Level Lists Source: https://github.com/a-bonus/google-docs-mcp/blob/main/SAMPLE_TASKS.md Creates a project plan with nested task lists, applying Heading styles for phases, numbered lists for tasks, and indented sub-lists for sub-tasks, with consistent formatting for owners and deadlines. ```text Task: "Create a project plan with properly formatted nested task lists." Steps: 1. Insert the project title and apply Heading 1 style 2. Create main project phases with Heading 2 style 3. For each phase, create a properly formatted numbered list of tasks 4. Create sub-tasks with indented, properly formatted sub-lists 5. Apply consistent formatting to all list levels 6. Format task owners' names in bold 7. Format dates and deadlines with a consistent style ``` -------------------------------- ### Get Table Structure Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/02-tools-google-docs.md Fetches the detailed structure, including row and column counts and cell content, for a specific table within a Google Document. Requires document ID and table ID. ```typescript async function getTableStructure(args: { documentId: string tableId: string tabId?: string }): Promise ``` -------------------------------- ### Search for Project Documents Source: https://github.com/a-bonus/google-docs-mcp/blob/main/SAMPLE_TASKS.md Utilize searchGoogleDocs to find documents relevant to the project. This is crucial for identifying files that need to be organized. ```python documents = searchGoogleDocs('project: My Project') ``` -------------------------------- ### Initialize Google API Clients Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/01-overview.md Initializes Google API clients. In local mode, it loads credentials from environment variables or a local token file. In remote mode, it's called per-request with current user credentials. ```typescript async initializeGoogleClient(): Promise { // ... implementation details ... return { authClient: // ..., googleDocs: // ..., googleDrive: // ..., googleSheets: // ..., googleScript: // ..., googleGmail: // ..., googleCalendar: // ... }; } ``` -------------------------------- ### Build the Server Code Source: https://github.com/a-bonus/google-docs-mcp/blob/main/docs/index.html Compile the TypeScript server code into JavaScript using the npm build script. This prepares the code for execution by Node.js. ```bash npm run build ``` -------------------------------- ### Insert Markdown into Google Docs Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/01-overview.md Converts provided Markdown content into Google Docs API requests and executes them. Options include specifying an insertion start index, targeting a specific tab, and treating the first H1 as a title. ```typescript async insertMarkdown(docs, documentId, markdown, options?): Promise ``` -------------------------------- ### Deploy Google Docs MCP Server to Cloud Run Source: https://github.com/a-bonus/google-docs-mcp/blob/main/README.md Deploy the Google Docs MCP Server to Google Cloud Run for remote access. This command sets up environment variables for authentication and service URL. ```bash gcloud run deploy google-docs-mcp \ --source . \ --region europe-west3 \ --port 8080 \ --allow-unauthenticated \ --set-env-vars "^|^MCP_TRANSPORT=httpStream|BASE_URL=https://your-service.run.app|GOOGLE_CLIENT_ID=...|GOOGLE_CLIENT_SECRET=...|TOKEN_STORE=firestore|JWT_SIGNING_KEY=your-secret-key" ``` -------------------------------- ### Configure MCP Client for Remote Google Docs Server Source: https://github.com/a-bonus/google-docs-mcp/blob/main/README.md Configure your MCP client to connect to a remotely deployed Google Docs MCP Server via its URL. This bypasses local setup and uses MCP OAuth 2.1 for authentication. ```json { "mcpServers": { "google-docs": { "type": "streamableHttp", "url": "https://your-service.run.app/mcp" } } } ``` -------------------------------- ### Configure MCP Server in VS Code Settings Source: https://github.com/a-bonus/google-docs-mcp/blob/main/vscode.md Add a new server configuration for Google Docs and Drive integration in VS Code's MCP settings. Ensure the command and arguments point to your MCP server's entry point. ```json { "google-docs-drive": { "command": "node", "args": ["${workspaceFolder}/dist/index.js"], "env": { "NODE_ENV": "production" } } } ``` -------------------------------- ### Sample Process CPU Usage Source: https://github.com/a-bonus/google-docs-mcp/blob/main/README.md Sample the CPU usage of a process at intervals. This is a diagnostic tool for identifying high CPU consumption in specific processes. ```bash sample 1 10 ``` -------------------------------- ### Cloud Run Deployment Configuration (httpStream) Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/07-configuration.md Deploys the Google Docs MCP to Cloud Run using the httpStream transport. Sets up necessary environment variables including secrets, base URL, OAuth credentials, token store, project ID, and encryption keys. ```bash #!/bin/bash # Generate secrets JWT_KEY=$(openssl rand -hex 32) TOKEN_KEY=$(openssl rand -hex 32) # Deploy gcloud run deploy google-docs-mcp \ --source . \ --region us-central1 \ --port 8080 \ --allow-unauthenticated \ --set-env-vars "^|^MCP_TRANSPORT=httpStream|BASE_URL=https://docs-mcp.example.com|GOOGLE_CLIENT_ID=123456|GOOGLE_CLIENT_SECRET=abc123|TOKEN_STORE=firestore|GCLOUD_PROJECT=my-project|JWT_SIGNING_KEY=${JWT_KEY}|TOKEN_ENCRYPTION_KEY=${TOKEN_KEY}|ALLOWED_DOMAINS=example.com" ``` -------------------------------- ### Manually Run MCP Server for Authorization Source: https://github.com/a-bonus/google-docs-mcp/blob/main/vscode.md If authentication issues arise, manually run the MCP server from your project directory to re-authorize. This process generates a new token.json file. ```bash cd /path/to/your/mcp-googledocs-server node dist/index.js ``` -------------------------------- ### Domain Folder Structure Source: https://github.com/a-bonus/google-docs-mcp/blob/main/src/tools/README.md Each domain folder contains an index.ts router, a README.md for documentation, and individual tool files. ```plaintext tools/docs/ # Google Docs API operations tools/drive/ # Google Drive file and folder management tools/sheets/ # Google Sheets operations tools/gmail/ # Gmail message and label operations tools/calendar/ # Google Calendar event operations tools/utils/ # Cross-cutting workflow utilities ``` -------------------------------- ### Run MCP Manually for Debugging Source: https://github.com/a-bonus/google-docs-mcp/blob/main/README.md Use this command to run the MCP manually and check for errors in the standard error output. This is useful for diagnosing server startup problems. ```bash npx @a-bonus/google-docs-mcp ``` -------------------------------- ### Run Vitest Tests Source: https://github.com/a-bonus/google-docs-mcp/blob/main/CONTRIBUTING.md Use these npm commands to execute tests with Vitest. The `-- --watch` flag enables watch mode for continuous testing. ```bash npm test ``` ```bash npm test -- --watch ``` -------------------------------- ### Service Account Authentication for Google Docs MCP Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/01-overview.md Use this command for Google Workspace domain-wide delegation with a service account. Ensure the SERVICE_ACCOUNT_PATH and GOOGLE_IMPERSONATE_USER environment variables are set correctly. ```bash SERVICE_ACCOUNT_PATH=/path/to/service-account.json \ GOOGLE_IMPERSONATE_USER=user@domain.com \ npx @a-bonus/google-docs-mcp ``` -------------------------------- ### Configure mcp_config.json for Google Docs Server Source: https://github.com/a-bonus/google-docs-mcp/blob/main/docs/index.html This JSON snippet shows how to configure the mcp_config.json file to specify the server's command-line arguments, including the absolute path to the server script. Ensure the path is correct and absolute. ```json { "mcpServers": [ { "command": "node /H/TO/YOUR/CLONED/REPO/mcp-googledocs-server/dist/server.js", "args": [ "--config", "/H/TO/YOUR/CLONED/REPO/mcp-googledocs-server/mcp_config.json" ], "env": {} } ] } ``` -------------------------------- ### Delete Token File and Re-authorize Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/08-errors.md Instructions to fix authentication issues by deleting the local token file and re-authorizing the Google Docs MCP client. ```bash # Or: Delete token file and re-authorize rm ~/.config/google-docs-mcp/token.json npx @a-bonus/google-docs-mcp auth ``` -------------------------------- ### Markdown Workflow for Google Docs Source: https://github.com/a-bonus/google-docs-mcp/blob/main/README.md Demonstrates the round-trip markdown workflow for reading and updating Google Docs. ```javascript readDocument with format='markdown' ``` ```javascript replaceDocumentWithMarkdown ``` -------------------------------- ### Authorize Google Docs MCP Server Source: https://github.com/a-bonus/google-docs-mcp/blob/main/README.md Use this command to authorize the Google Docs MCP Server. It opens a browser for Google authorization and saves the refresh token locally. ```bash GOOGLE_CLIENT_ID="your-client-id" \ GOOGLE_CLIENT_SECRET="your-client-secret" \ npx -y @a-bonus/google-docs-mcp auth ``` -------------------------------- ### insertTableWithData Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/02-tools-google-docs.md Creates a table in a Google Document and pre-fills it with provided data. The data is supplied as a 2D array of strings. ```APIDOC ## insertTableWithData ### Description Creates a table pre-filled with data. ### Method ```typescript async function insertTableWithData(args: { documentId: string index: number data: string[][] tabId?: string }): Promise ``` ### Parameters #### Path Parameters - **documentId** (string) - yes - Document ID - **index** (number) - yes - 1-based insertion index - **data** (string[][]) - yes - 2D array of cell values [[row1], [row2], ...] - **tabId** (string) - no - Tab ID ### Request Example ```javascript await insertTableWithData({ documentId: '1-5XzW3YN8_Q1X2Y3Z', index: 100, data: [ ['Name', 'Score', 'Grade'], ['Alice', '95', 'A'], ['Bob', '87', 'B'] ] }); ``` ``` -------------------------------- ### Tool Registration Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/01-overview.md Pattern for registering tools within the MCP server. ```APIDOC ## register ### Description Registers a tool with the FastMCP server. ### Parameters - `server` (FastMCP) - The MCP server instance. ### Tool Object Structure - `name` (string) - The name of the tool (camelCase). - `description` (string) - A description of the tool's functionality. - `parameters` (Zod Schema) - A Zod schema defining the tool's input parameters. - `execute` (function) - An asynchronous function that executes the tool's logic. - `args` - The arguments conforming to the `parameters` schema. - `{ log }` - A context object containing a logging function. - The `execute` function should return a string (stringified JSON for complex results) or throw a `UserError` for client-facing messages. ``` -------------------------------- ### Create Google Drive Folder Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/04-tools-google-drive-gmail-calendar.md Creates a new folder in Google Drive. Specify a name and optionally a parent folder ID. ```typescript async function createFolder(args: { name: string parentFolderId?: string }): Promise ``` -------------------------------- ### Generate Report from Template Source: https://github.com/a-bonus/google-docs-mcp/blob/main/SAMPLE_TASKS.md Use createFromTemplate to generate new reports based on existing templates. This automates the creation of standardized documents. ```python new_report_id = createFromTemplate(template_id, 'New Report', replacements={'{{DATE}}': '2023-10-27', '{{NAME}}': 'John Doe'}) ``` -------------------------------- ### Profile Support for Multiple Google Docs MCP Accounts Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/01-overview.md Configure different Google Docs MCP profiles to manage multiple accounts. Each profile saves its token to a dedicated subdirectory within the configuration path. ```bash GOOGLE_MCP_PROFILE=work npx @a-bonus/google-docs-mcp # Token saved to ~/.config/google-docs-mcp/work/token.json ``` ```bash GOOGLE_MCP_PROFILE=personal npx @a-bonus/google-docs-mcp # Token saved to ~/.config/google-docs-mcp/personal/token.json ``` -------------------------------- ### Set Service Account Path Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/07-configuration.md Configure the path to your Google Service Account JSON key file. This enables domain-wide delegation for automated scripts in local mode. ```bash export SERVICE_ACCOUNT_PATH="/path/to/service-account-key.json" npx @a-bonus/google-docs-mcp ``` -------------------------------- ### Authenticate with Environment Variables Source: https://github.com/a-bonus/google-docs-mcp/blob/main/CONTRIBUTING.md Use environment variables for Google OAuth client ID and secret to authenticate. This method is suitable for npx consumers. ```bash GOOGLE_CLIENT_ID="your-client-id" \ GOOGLE_CLIENT_SECRET="your-client-secret" \ npm start auth ``` -------------------------------- ### Register a Tool with FastMCP Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/01-overview.md Use this pattern to register new tools with the FastMCP server. Ensure tool names are camelCase and parameters are strictly typed with Zod. The execute function should return a string, and client-facing errors should throw UserError. ```typescript export function register(server: FastMCP) { server.addTool({ name: 'toolName', description: '...', parameters: z.strictObject({ /* Zod schema */ }), execute: async (args, { log }) => { const client = await getClientFunction(); // Implementation return resultString; } }); } ``` -------------------------------- ### Configure MCP Profile for Multiple Accounts Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/07-configuration.md Set a profile name to manage separate Google account tokens. This is useful for running multiple servers with different Google accounts, storing tokens in distinct locations. ```bash # Set up work account export GOOGLE_CLIENT_ID="..." GOOGLE_CLIENT_SECRET="..." export GOOGLE_MCP_PROFILE="work" npx @a-bonus/google-docs-mcp auth # Token stored to ~/.config/google-docs-mcp/work/token.json # Later: Set up personal account export GOOGLE_CLIENT_ID="..." GOOGLE_CLIENT_SECRET="..." export GOOGLE_MCP_PROFILE="personal" npx @a-bonus/google-docs-mcp auth # Token stored to ~/.config/google-docs-mcp/personal/token.json ``` -------------------------------- ### List Folder Contents Source: https://github.com/a-bonus/google-docs-mcp/blob/main/SAMPLE_TASKS.md Catalog all folders and their contents using listFolderContents. This is essential for generating a comprehensive file inventory. ```python contents = listFolderContents(folder_id) ``` -------------------------------- ### Enabling Debug Logs for MCP Server Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/08-errors.md Commands to view server logs for debugging. The first command is for local mode, showing errors, while the second is for remote mode on Cloud Run. ```bash # View server logs (local mode) npx @a-bonus/google-docs-mcp 2>&1 | grep ERROR # For remote mode, check Cloud Run logs gcloud run logs read google-docs-mcp --region=us-central1 --limit=100 ``` -------------------------------- ### createFolder Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/04-tools-google-drive-gmail-calendar.md Creates a new folder in Google Drive. You can specify a name and an optional parent folder ID. Returns the ID and URL of the newly created folder. ```APIDOC ## createFolder ### Description Creates a new folder in Google Drive. ### Method Not applicable (SDK function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **name** (string) - Required - Folder name - **parentFolderId** (string) - Optional - Parent folder ID (default: root) ### Returns JSON with folder ID and URL ``` -------------------------------- ### Common Errors for quickAddEvent Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/08-errors.md Errors that can occur when using the quick add event functionality. These typically involve issues with parsing the event text or problems with the specified calendar. ```text "Unable to parse event text." "Calendar not found." ``` -------------------------------- ### Tag a New Release Commit Source: https://github.com/a-bonus/google-docs-mcp/blob/main/CONTRIBUTING.md After updating the version and pushing to main, tag the commit to trigger the release workflow. Replace 'v1.2.3' with the actual version number. ```bash git tag v1.2.3 && git push origin v1.2.3 ``` -------------------------------- ### Create Response Form with Structured Fields Source: https://github.com/a-bonus/google-docs-mcp/blob/main/SAMPLE_TASKS.md Creates section headers, inserts tables for response areas, adds form fields with instructions, distinguishes instructions from response areas, and uses consistent formatting for lists and spacing. ```text Task: "Create a form-like document with fields for respondents to complete." Steps: 1. Create section headers for different parts of the form 2. Insert tables for structured response areas 3. Add form fields with clear instructions 4. Use formatting to distinguish between instructions and response areas 5. Add checkbox lists using special characters with consistent formatting 6. Apply consistent spacing and alignment throughout ``` -------------------------------- ### Create Subfolders Source: https://github.com/a-bonus/google-docs-mcp/blob/main/SAMPLE_TASKS.md Create subfolders within a main project folder to organize different aspects of the project. This helps in categorizing documents, templates, and archives. ```python createFolder('Documents', parent_id=folder_id) createFolder('Templates', parent_id=folder_id) createFolder('Archive', parent_id=folder_id) ``` -------------------------------- ### downloadFile Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/04-tools-google-drive-gmail-calendar.md Downloads the content of a file from Google Drive. Returns the file content, which will be text for text files and base64-encoded content for binary files. ```APIDOC ## downloadFile ### Description Downloads a file's content from Google Drive. ### Method Not applicable (SDK function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **fileId** (string) - Required - File ID ### Returns File content (text files return text, binary files return base64-encoded content) ``` -------------------------------- ### createDocumentFromTemplate Source: https://github.com/a-bonus/google-docs-mcp/blob/main/_autodocs/04-tools-google-drive-gmail-calendar.md Creates a new Google Document from an existing template, allowing for a new title and optional folder placement. ```APIDOC ## createDocumentFromTemplate ### Description Creates a new document from an existing template. Requires the template document ID and a new title for the document. Optionally, a folder ID can be specified. ### Method `createDocumentFromTemplate` ### Parameters #### Query Parameters - **templateDocumentId** (string) - Required - Template document ID - **newTitle** (string) - Required - Title for new document - **folderId** (string) - Optional - Folder ID (default: same as template) ### Returns JSON with new document ID. ``` -------------------------------- ### List Smart Chips in Document Source: https://github.com/a-bonus/google-docs-mcp/blob/main/docs/planning-doc-formatting-spec.md Reads smart chips from a document or a specified range. Useful for retrieving chip information. ```typescript { documentId: string; tabId?: string; startIndex?: number; endIndex?: number; } ``` -------------------------------- ### Rename Documents Source: https://github.com/a-bonus/google-docs-mcp/blob/main/SAMPLE_TASKS.md Apply consistent naming conventions to documents using renameFile. This improves document discoverability and organization. ```python renameFile(document_id, 'New Document Name') ```