#
tokens: 49530/50000 17/18 files (page 1/2)
lines: off (toggle) GitHub
raw markdown copy
This is page 1 of 2. Use http://codebase.md/a-bonus/google-docs-mcp?page={x} to view the full context.

# Directory Structure

```
├── .DS_Store
├── .gitignore
├── .repomix
│   └── bundles.json
├── assets
│   └── google.docs.mcp.1.gif
├── claude.md
├── docs
│   └── index.html
├── google docs mcp.mp4
├── index.js
├── LICENSE
├── package-lock.json
├── package.json
├── pages
│   └── pages.md
├── README.md
├── repomix-output.txt.xml
├── SAMPLE_TASKS.md
├── src
│   ├── auth.ts
│   ├── backup
│   │   ├── auth.ts.bak
│   │   └── server.ts.bak
│   ├── googleDocsApiHelpers.ts
│   ├── server.ts
│   └── types.ts
├── tests
│   ├── helpers.test.js
│   └── types.test.js
├── tsconfig.json
└── vscode.md
```

# Files

--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------

```
# Node dependencies
node_modules/
dist/

# Credentials / Tokens
credentials.json
token.json

# Log files
*.log

# Environment variables (if you use a .env file later)
.env* 
```

--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------

```markdown
# Ultimate Google Docs & Drive MCP Server

![Demo Animation](assets/google.docs.mcp.1.gif)

Connect Claude Desktop (or other MCP clients) to your Google Docs and Google Drive!

> 🔥 **Check out [15 powerful tasks](SAMPLE_TASKS.md) you can accomplish with this enhanced server!**
> 📁 **NEW:** Complete Google Drive file management capabilities!

This comprehensive server uses the Model Context Protocol (MCP) and the `fastmcp` library to provide tools for reading, writing, formatting, structuring Google Documents, and managing your entire Google Drive. It acts as a powerful bridge, allowing AI assistants like Claude to interact with your documents and files programmatically with advanced capabilities.

**Features:**

### Document Access & Editing
- **Read Documents:** Read content with `readGoogleDoc` (plain text, JSON structure, or markdown)
- **Append to Documents:** Add text to documents with `appendToGoogleDoc`
- **Insert Text:** Place text at specific positions with `insertText`
- **Delete Content:** Remove content from a document with `deleteRange`

### Formatting & Styling
- **Text Formatting:** Apply rich styling with `applyTextStyle` (bold, italic, colors, etc.)
- **Paragraph Formatting:** Control paragraph layout with `applyParagraphStyle` (alignment, spacing, etc.)
- **Find & Format:** Format by text content using `formatMatchingText` (legacy support)

### Document Structure
- **Tables:** Create tables with `insertTable`
- **Page Breaks:** Insert page breaks with `insertPageBreak`
- **Images:** Insert images from URLs with `insertImageFromUrl`, or upload local images with `insertLocalImage`
- **Experimental Features:** Tools like `fixListFormatting` for automatic list detection

### 🆕 Comment Management
- **List Comments:** View all comments in a document with `listComments` (shows author, date, and quoted text)
- **Get Comment Details:** Get specific comment with replies using `getComment`
- **Add Comments:** Create new comments anchored to text with `addComment`
- **Reply to Comments:** Add replies to existing comments with `replyToComment`
- **Resolve Comments:** Mark comments as resolved with `resolveComment`
- **Delete Comments:** Remove comments from documents with `deleteComment`

### 🆕 Google Drive File Management
- **Document Discovery:** Find and list documents with `listGoogleDocs`, `searchGoogleDocs`, `getRecentGoogleDocs`
- **Document Information:** Get detailed metadata with `getDocumentInfo`
- **Folder Management:** Create folders (`createFolder`), list contents (`listFolderContents`), get info (`getFolderInfo`)
- **File Operations:** Move (`moveFile`), copy (`copyFile`), rename (`renameFile`), delete (`deleteFile`)
- **Document Creation:** Create new docs (`createDocument`) or from templates (`createFromTemplate`)

### Integration
- **Google Authentication:** Secure OAuth 2.0 authentication with full Drive access
- **MCP Compliant:** Designed for use with Claude and other MCP clients
- **VS Code Integration:** [Setup guide](vscode.md) for VS Code MCP extension

---

## Prerequisites

Before you start, make sure you have:

1.  **Node.js and npm:** A recent version of Node.js (which includes npm) installed on your computer. You can download it from [nodejs.org](https://nodejs.org/). (Version 18 or higher recommended).
2.  **Git:** Required for cloning this repository. ([Download Git](https://git-scm.com/downloads)).
3.  **A Google Account:** The account that owns or has access to the Google Docs you want to interact with.
4.  **Command Line Familiarity:** Basic comfort using a terminal or command prompt (like Terminal on macOS/Linux, or Command Prompt/PowerShell on Windows).
5.  **Claude Desktop (Optional):** If your goal is to connect this server to Claude, you'll need the Claude Desktop application installed.

---

## Setup Instructions

Follow these steps carefully to get your own instance of the server running.

### Step 1: Google Cloud Project & Credentials (The Important Bit!)

This server needs permission to talk to Google APIs on your behalf. You'll create special "keys" (credentials) that only your server will use.

1.  **Go to Google Cloud Console:** Open your web browser and go to the [Google Cloud Console](https://console.cloud.google.com/). You might need to log in with your Google Account.
2.  **Create or Select a Project:**
    - If you don't have a project, click the project dropdown near the top and select "NEW PROJECT". Give it a name (e.g., "My MCP Docs Server") and click "CREATE".
    - If you have existing projects, you can select one or create a new one.
3.  **Enable APIs:** You need to turn on the specific Google services this server uses.
    - In the search bar at the top, type "APIs & Services" and select "Library".
    - Search for "**Google Docs API**" and click on it. Then click the "**ENABLE**" button.
    - Search for "**Google Drive API**" and click on it. Then click the "**ENABLE**" button (this is often needed for finding files or permissions).
4.  **Configure OAuth Consent Screen:** This screen tells users (usually just you) what your app wants permission for.
    - On the left menu, click "APIs & Services" -> "**OAuth consent screen**".
    - Choose User Type: Select "**External**" and click "CREATE".
    - Fill in App Information:
      - **App name:** Give it a name users will see (e.g., "Claude Docs MCP Access").
      - **User support email:** Select your email address.
      - **Developer contact information:** Enter your email address.
    - Click "**SAVE AND CONTINUE**".
    - **Scopes:** Click "**ADD OR REMOVE SCOPES**". Search for and add the following scopes:
      - `https://www.googleapis.com/auth/documents` (Allows reading/writing docs)
      - `https://www.googleapis.com/auth/drive.file` (Allows access to specific files opened/created by the app)
      - Click "**UPDATE**".
    - Click "**SAVE AND CONTINUE**".
    - **Test Users:** Click "**ADD USERS**". Enter the same Google email address you are logged in with. Click "**ADD**". This allows _you_ to use the app while it's in "testing" mode.
    - Click "**SAVE AND CONTINUE**". Review the summary and click "**BACK TO DASHBOARD**".
5.  **Create Credentials (The Keys!):**
    - On the left menu, click "APIs & Services" -> "**Credentials**".
    - Click "**+ CREATE CREDENTIALS**" at the top and choose "**OAuth client ID**".
    - **Application type:** Select "**Desktop app**" from the dropdown.
    - **Name:** Give it a name (e.g., "MCP Docs Desktop Client").
    - Click "**CREATE**".
6.  **⬇️ DOWNLOAD THE CREDENTIALS FILE:** A box will pop up showing your Client ID. Click the "**DOWNLOAD JSON**" button.
    - Save this file. It will likely be named something like `client_secret_....json`.
    - **IMPORTANT:** Rename the downloaded file to exactly `credentials.json`.
7.  ⚠️ **SECURITY WARNING:** Treat this `credentials.json` file like a password! Do not share it publicly, and **never commit it to GitHub.** Anyone with this file could potentially pretend to be _your application_ (though they'd still need user consent to access data).

### Step 2: Get the Server Code

1.  **Clone the Repository:** Open your terminal/command prompt and run:
    ```bash
    git clone https://github.com/a-bonus/google-docs-mcp.git mcp-googledocs-server
    ```
2.  **Navigate into Directory:**
    ```bash
    cd mcp-googledocs-server
    ```
3.  **Place Credentials:** Move or copy the `credentials.json` file you downloaded and renamed (from Step 1.6) directly into this `mcp-googledocs-server` folder.

### Step 3: Install Dependencies

Your server needs some helper libraries specified in the `package.json` file.

1.  In your terminal (make sure you are inside the `mcp-googledocs-server` directory), run:
    ```bash
    npm install
    ```
    This will download and install all the necessary packages into a `node_modules` folder.

### Step 4: Build the Server Code

The server is written in TypeScript (`.ts`), but we need to compile it into JavaScript (`.js`) that Node.js can run directly.

1.  In your terminal, run:
    ```bash
    npm run build
    ```
    This uses the TypeScript compiler (`tsc`) to create a `dist` folder containing the compiled JavaScript files.

### Step 5: First Run & Google Authorization (One Time Only)

Now you need to run the server once manually to grant it permission to access your Google account data. This will create a `token.json` file that saves your permission grant.

1.  In your terminal, run the _compiled_ server using `node`:
    ```bash
    node ./dist/server.js
    ```
2.  **Watch the Terminal:** The script will print:
    - Status messages (like "Attempting to authorize...").
    - An "Authorize this app by visiting this url:" message followed by a long `https://accounts.google.com/...` URL.
3.  **Authorize in Browser:**
    - Copy the entire long URL from the terminal.
    - Paste the URL into your web browser and press Enter.
    - Log in with the **same Google account** you added as a Test User in Step 1.4.
    - Google will show a screen asking for permission for your app ("Claude Docs MCP Access" or similar) to access Google Docs/Drive. Review and click "**Allow**" or "**Grant**".
4.  **Get the Authorization Code:**
    - After clicking Allow, your browser will likely try to redirect to `http://localhost` and show a **"This site can't be reached" error**. **THIS IS NORMAL!**
    - Look **carefully** at the URL in your browser's address bar. It will look like `http://localhost/?code=4/0Axxxxxxxxxxxxxx&scope=...`
    - Copy the long string of characters **between `code=` and the `&scope` part**. This is your single-use authorization code.
5.  **Paste Code into Terminal:** Go back to your terminal where the script is waiting ("Enter the code from that page here:"). Paste the code you just copied.
6.  **Press Enter.**
7.  **Success!** The script should print:
    - "Authentication successful!"
    - "Token stored to .../token.json"
    - It will then finish starting and likely print "Awaiting MCP client connection via stdio..." or similar, and then exit (or you can press `Ctrl+C` to stop it).
8.  ✅ **Check:** You should now see a new file named `token.json` in your `mcp-googledocs-server` folder.
9.  ⚠️ **SECURITY WARNING:** This `token.json` file contains the key that allows the server to access your Google account _without_ asking again. Protect it like a password. **Do not commit it to GitHub.** The included `.gitignore` file should prevent this automatically.

### Step 6: Configure Claude Desktop (Optional)

If you want to use this server with Claude Desktop, you need to tell Claude how to run it.

1.  **Find Your Absolute Path:** You need the full path to the server code.
    - In your terminal, make sure you are still inside the `mcp-googledocs-server` directory.
    - Run the `pwd` command (on macOS/Linux) or `cd` (on Windows, just displays the path).
    - Copy the full path (e.g., `/Users/yourname/projects/mcp-googledocs-server` or `C:\Users\yourname\projects\mcp-googledocs-server`).
2.  **Locate `mcp_config.json`:** Find Claude's configuration file:
    - **macOS:** `~/Library/Application Support/Claude/mcp_config.json` (You might need to use Finder's "Go" -> "Go to Folder..." menu and paste `~/Library/Application Support/Claude/`)
    - **Windows:** `%APPDATA%\Claude\mcp_config.json` (Paste `%APPDATA%\Claude` into File Explorer's address bar)
    - **Linux:** `~/.config/Claude/mcp_config.json`
    - _If the `Claude` folder or `mcp_config.json` file doesn't exist, create them._
3.  **Edit `mcp_config.json`:** Open the file in a text editor. Add or modify the `mcpServers` section like this, **replacing `/PATH/TO/YOUR/CLONED/REPO` with the actual absolute path you copied in Step 6.1**:

    ```json
    {
      "mcpServers": {
        "google-docs-mcp": {
          "command": "node",
          "args": [
            "/PATH/TO/YOUR/CLONED/REPO/mcp-googledocs-server/dist/server.js"
          ],
          "env": {}
        }
        // Add commas here if you have other servers defined
      }
      // Other Claude settings might be here
    }
    ```

    - **Make sure the path in `"args"` is correct and absolute!**
    - If the file already existed, carefully merge this entry into the existing `mcpServers` object. Ensure the JSON is valid (check commas!).

4.  **Save `mcp_config.json`.**
5.  **Restart Claude Desktop:** Close Claude completely and reopen it.

---

## Usage with Claude Desktop

Once configured, you should be able to use the tools in your chats with Claude:

- "Use the `google-docs-mcp` server to read the document with ID `YOUR_GOOGLE_DOC_ID`."
- "Can you get the content of Google Doc `YOUR_GOOGLE_DOC_ID`?"
- "Append 'This was added by Claude!' to document `YOUR_GOOGLE_DOC_ID` using the `google-docs-mcp` tool."

### Advanced Usage Examples:
- **Text Styling**: "Use `applyTextStyle` to make the text 'Important Section' bold and red (#FF0000) in document `YOUR_GOOGLE_DOC_ID`."
- **Paragraph Styling**: "Use `applyParagraphStyle` to center-align the paragraph containing 'Title Here' in document `YOUR_GOOGLE_DOC_ID`."
- **Table Creation**: "Insert a 3x4 table at index 500 in document `YOUR_GOOGLE_DOC_ID` using the `insertTable` tool."
- **Image Insertion**: "Use `insertImageFromUrl` to insert an image from 'https://example.com/image.png' at index 100 in document `YOUR_GOOGLE_DOC_ID`."
- **Local Image Upload**: "Use `insertLocalImage` to upload '/path/to/image.jpg' and insert it at index 200 in document `YOUR_GOOGLE_DOC_ID`."
- **Legacy Formatting**: "Use `formatMatchingText` to find the second instance of 'Project Alpha' and make it blue (#0000FF) in doc `YOUR_GOOGLE_DOC_ID`."

Remember to replace `YOUR_GOOGLE_DOC_ID` with the actual ID from a Google Doc's URL (the long string between `/d/` and `/edit`).

Claude will automatically launch your server in the background when needed using the command you provided. You do **not** need to run `node ./dist/server.js` manually anymore.

---

## Image Insertion

This server provides two ways to insert images into Google Documents:

### 1. Insert from Public URL (`insertImageFromUrl`)

Inserts an image directly from a publicly accessible URL. The image URL must be accessible without authentication.

**Parameters:**
- `documentId`: The Google Document ID
- `imageUrl`: Publicly accessible URL (http:// or https://)
- `index`: Position in the document (1-based indexing)
- `width` (optional): Image width in points
- `height` (optional): Image height in points

**Example:**
```
"Insert an image from https://example.com/logo.png at index 100 in document YOUR_DOC_ID"
```

### 2. Upload Local Image (`insertLocalImage`)

Uploads a local image file to Google Drive and inserts it into the document. This is a two-step process that:
1. Uploads the image to Google Drive (by default to the same folder as the document)
2. Makes the image publicly readable
3. Inserts the image into the document using its Drive URL

**Parameters:**
- `documentId`: The Google Document ID
- `localImagePath`: Absolute path to the local image file
- `index`: Position in the document (1-based indexing)
- `width` (optional): Image width in points
- `height` (optional): Image height in points
- `uploadToSameFolder` (optional, default: true): If true, uploads to the document's folder; if false, uploads to Drive root

**Supported formats:** .jpg, .jpeg, .png, .gif, .bmp, .webp, .svg

**Example:**
```
"Upload and insert the image at /Users/myname/Pictures/chart.png at index 200 in document YOUR_DOC_ID with width 400 and height 300"
```

**Note:** The uploaded image will be made publicly readable so it can be displayed in the document. The image file will remain in your Google Drive and can be managed separately.

---

## Security & Token Storage

- **`.gitignore`:** This repository includes a `.gitignore` file which should prevent you from accidentally committing your sensitive `credentials.json` and `token.json` files. **Do not remove these lines from `.gitignore`**.
- **Token Storage:** This server stores the Google authorization token (`token.json`) directly in the project folder for simplicity during setup. In production or more security-sensitive environments, consider storing this token more securely, such as using system keychains, encrypted files, or dedicated secret management services.

---

## Troubleshooting

- **Claude shows "Failed" or "Could not attach":**
  - Double-check the absolute path in `mcp_config.json`.
  - Ensure you ran `npm run build` successfully and the `dist` folder exists.
  - Try running the command from `mcp_config.json` manually in your terminal: `node /PATH/TO/YOUR/CLONED/REPO/mcp-googledocs-server/dist/server.js`. Look for any errors printed.
  - Check the Claude Desktop logs (see the official MCP debugging guide).
  - Make sure all `console.log` status messages in the server code were changed to `console.error`.
- **Google Authorization Errors:**
  - Ensure you enabled the correct APIs (Docs, Drive).
  - Make sure you added your email as a Test User on the OAuth Consent Screen.
  - Verify the `credentials.json` file is correctly placed in the project root.

---

## License

This project is licensed under the MIT License - see the `LICENSE` file for details. (Note: You should add a `LICENSE` file containing the MIT License text to your repository).

```

--------------------------------------------------------------------------------
/claude.md:
--------------------------------------------------------------------------------

```markdown
Okay, this is a significant undertaking. Building the "absolute best" server involves adding many complex features. I will provide:
The full code for a substantially enhanced server.ts and the necessary new helper files (googleDocsApiHelpers.ts, types.ts). This code will include implementations for several key advanced features discussed and well-defined stubs for others, indicating where further development would go.
Step-by-step instructions on how to integrate this new code into your existing project structure.
Disclaimer: This code is extensive and demonstrates the structure and approach for advanced features. It includes implementations for key examples but leaves many others as stubs (// TODO: Implement... or throwing NotImplementedError). Thorough testing and potentially significant refinement would be needed for production use, especially for complex logic like fixListFormatting or robust index handling across multiple edits. Error handling is included but could be further enhanced.
Phase 1: The Code

1. New File: src/types.ts
   // src/types.ts
   import { z } from 'zod';
   import { docs_v1 } from 'googleapis';

// --- Helper function for hex color validation ---
export const hexColorRegex = /^#?([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/;
export const validateHexColor = (color: string) => hexColorRegex.test(color);

// --- Helper function for Hex to RGB conversion ---
export function hexToRgbColor(hex: string): docs_v1.Schema$RgbColor | null {
if (!hex) return null;
let hexClean = hex.startsWith('#') ? hex.slice(1) : hex;

if (hexClean.length === 3) {
hexClean = hexClean[0] + hexClean[0] + hexClean[1] + hexClean[1] + hexClean[2] + hexClean[2];
}
if (hexClean.length !== 6) return null;
const bigint = parseInt(hexClean, 16);
if (isNaN(bigint)) return null;

const r = ((bigint >> 16) & 255) / 255;
const g = ((bigint >> 8) & 255) / 255;
const b = (bigint & 255) / 255;

return { red: r, green: g, blue: b };
}

// --- Zod Schema Fragments for Reusability ---

export const DocumentIdParameter = z.object({
documentId: z.string().describe('The ID of the Google Document (from the URL).'),
});

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

export const OptionalRangeParameters = z.object({
startIndex: z.number().int().min(1).optional().describe('Optional: The starting index of the text range (inclusive, starts from 1). If omitted, might apply to a found element or whole paragraph.'),
endIndex: z.number().int().min(1).optional().describe('Optional: The ending index of the text range (exclusive). If omitted, might apply to a found element or whole paragraph.'),
}).refine(data => !data.startIndex || !data.endIndex || data.endIndex > data.startIndex, {
message: "If both startIndex and endIndex are provided, endIndex must be greater than startIndex",
path: ["endIndex"],
});

export const TextFindParameter = z.object({
textToFind: z.string().min(1).describe('The exact text string to locate.'),
matchInstance: z.number().int().min(1).optional().default(1).describe('Which instance of the text to target (1st, 2nd, etc.). Defaults to 1.'),
});

// --- Style Parameter Schemas ---

export const TextStyleParameters = z.object({
bold: z.boolean().optional().describe('Apply bold formatting.'),
italic: z.boolean().optional().describe('Apply italic formatting.'),
underline: z.boolean().optional().describe('Apply underline formatting.'),
strikethrough: z.boolean().optional().describe('Apply strikethrough formatting.'),
fontSize: z.number().min(1).optional().describe('Set font size (in points, e.g., 12).'),
fontFamily: z.string().optional().describe('Set font family (e.g., "Arial", "Times New Roman").'),
foregroundColor: z.string()
.refine(validateHexColor, { message: "Invalid hex color format (e.g., #FF0000 or #F00)" })
.optional()
.describe('Set text color using hex format (e.g., "#FF0000").'),
backgroundColor: z.string()
.refine(validateHexColor, { message: "Invalid hex color format (e.g., #00FF00 or #0F0)" })
.optional()
.describe('Set text background color using hex format (e.g., "#FFFF00").'),
linkUrl: z.string().url().optional().describe('Make the text a hyperlink pointing to this URL.'),
// clearDirectFormatting: z.boolean().optional().describe('If true, attempts to clear all direct text formatting within the range before applying new styles.') // Harder to implement perfectly
}).describe("Parameters for character-level text formatting.");

// Subset of TextStyle used for passing to helpers
export type TextStyleArgs = z.infer<typeof TextStyleParameters>;

export const ParagraphStyleParameters = z.object({
alignment: z.enum(['LEFT', 'CENTER', 'RIGHT', 'JUSTIFIED']).optional().describe('Paragraph alignment.'),
indentStart: z.number().min(0).optional().describe('Left indentation in points.'),
indentEnd: z.number().min(0).optional().describe('Right indentation in points.'),
spaceAbove: z.number().min(0).optional().describe('Space before the paragraph in points.'),
spaceBelow: z.number().min(0).optional().describe('Space after the paragraph in points.'),
namedStyleType: z.enum([
'NORMAL_TEXT', 'TITLE', 'SUBTITLE',
'HEADING_1', 'HEADING_2', 'HEADING_3', 'HEADING_4', 'HEADING_5', 'HEADING_6'
]).optional().describe('Apply a built-in named paragraph style (e.g., HEADING_1).'),
keepWithNext: z.boolean().optional().describe('Keep this paragraph together with the next one on the same page.'),
// Borders are more complex, might need separate objects/tools
// clearDirectFormatting: z.boolean().optional().describe('If true, attempts to clear all direct paragraph formatting within the range before applying new styles.') // Harder to implement perfectly
}).describe("Parameters for paragraph-level formatting.");

// Subset of ParagraphStyle used for passing to helpers
export type ParagraphStyleArgs = z.infer<typeof ParagraphStyleParameters>;

// --- Combination Schemas for Tools ---

export const ApplyTextStyleToolParameters = DocumentIdParameter.extend({
// Target EITHER by range OR by finding text
target: z.union([
RangeParameters,
TextFindParameter
]).describe("Specify the target range either by start/end indices or by finding specific text."),
style: TextStyleParameters.refine(
styleArgs => Object.values(styleArgs).some(v => v !== undefined),
{ message: "At least one text style option must be provided." }
).describe("The text styling to apply.")
});
export type ApplyTextStyleToolArgs = z.infer<typeof ApplyTextStyleToolParameters>;

export const ApplyParagraphStyleToolParameters = DocumentIdParameter.extend({
// Target EITHER by range OR by finding text (tool logic needs to find paragraph boundaries)
target: z.union([
RangeParameters, // User provides paragraph start/end (less likely)
TextFindParameter.extend({
applyToContainingParagraph: z.literal(true).default(true).describe("Must be true. Indicates the style applies to the whole paragraph containing the found text.")
}),
z.object({ // Target by specific index within the paragraph
indexWithinParagraph: z.number().int().min(1).describe("An index located anywhere within the target paragraph.")
})
]).describe("Specify the target paragraph either by start/end indices, by finding text within it, or by providing an index within it."),
style: ParagraphStyleParameters.refine(
styleArgs => Object.values(styleArgs).some(v => v !== undefined),
{ message: "At least one paragraph style option must be provided." }
).describe("The paragraph styling to apply.")
});
export type ApplyParagraphStyleToolArgs = z.infer<typeof ApplyParagraphStyleToolParameters>;

// --- Error Class ---
// Use FastMCP's UserError for client-facing issues
// Define a custom error for internal issues if needed
export class NotImplementedError extends Error {
constructor(message = "This feature is not yet implemented.") {
super(message);
this.name = "NotImplementedError";
}
}
Use code with caution.
TypeScript 2. New File: src/googleDocsApiHelpers.ts
// src/googleDocsApiHelpers.ts
import { google, docs_v1 } from 'googleapis';
import { OAuth2Client } from 'google-auth-library';
import { UserError } from 'fastmcp';
import { TextStyleArgs, ParagraphStyleArgs, hexToRgbColor, NotImplementedError } from './types.js';

type Docs = docs_v1.Docs; // Alias for convenience

// --- Constants ---
const MAX_BATCH_UPDATE_REQUESTS = 50; // Google API limits batch size

// --- Core Helper to Execute Batch Updates ---
export async function executeBatchUpdate(docs: Docs, documentId: string, requests: docs_v1.Schema$Request[]): Promise<docs_v1.Schema$BatchUpdateDocumentResponse> {
if (!requests || requests.length === 0) {
// console.warn("executeBatchUpdate called with no requests.");
return {}; // Nothing to do
}

    // TODO: Consider splitting large request arrays into multiple batches if needed
    if (requests.length > MAX_BATCH_UPDATE_REQUESTS) {
         console.warn(`Attempting batch update with ${requests.length} requests, exceeding typical limits. May fail.`);
    }

    try {
        const response = await docs.documents.batchUpdate({
            documentId: documentId,
            requestBody: { requests },
        });
        return response.data;
    } catch (error: any) {
        console.error(`Google API batchUpdate Error for doc ${documentId}:`, error.response?.data || error.message);
        // Translate common API errors to UserErrors
        if (error.code === 400 && error.message.includes('Invalid requests')) {
             // Try to extract more specific info if available
             const details = error.response?.data?.error?.details;
             let detailMsg = '';
             if (details && Array.isArray(details)) {
                 detailMsg = details.map(d => d.description || JSON.stringify(d)).join('; ');
             }
            throw new UserError(`Invalid request sent to Google Docs API. Details: ${detailMsg || error.message}`);
        }
        if (error.code === 404) throw new UserError(`Document not found (ID: ${documentId}). Check the ID.`);
        if (error.code === 403) throw new UserError(`Permission denied for document (ID: ${documentId}). Ensure the authenticated user has edit access.`);
        // Generic internal error for others
        throw new Error(`Google API Error (${error.code}): ${error.message}`);
    }

}

// --- Text Finding Helper ---
// NOTE: This is a simplified version. A robust version needs to handle
// text spanning multiple TextRuns, pagination, tables etc.
export async function findTextRange(docs: Docs, documentId: string, textToFind: string, instance: number = 1): Promise<{ startIndex: number; endIndex: number } | null> {
try {
const res = await docs.documents.get({
documentId,
fields: 'body(content(paragraph(elements(startIndex,endIndex,textRun(content)))))',
});

        if (!res.data.body?.content) return null;

        let fullText = '';
        const segments: { text: string, start: number, end: number }[] = [];
        res.data.body.content.forEach(element => {
            element.paragraph?.elements?.forEach(pe => {
                if (pe.textRun?.content && pe.startIndex && pe.endIndex) {
                    const content = pe.textRun.content;
                    fullText += content;
                    segments.push({ text: content, start: pe.startIndex, end: pe.endIndex });
                }
            });
        });

        let startIndex = -1;
        let endIndex = -1;
        let foundCount = 0;
        let searchStartIndex = 0;

        while (foundCount < instance) {
            const currentIndex = fullText.indexOf(textToFind, searchStartIndex);
            if (currentIndex === -1) break;

            foundCount++;
            if (foundCount === instance) {
                const targetStartInFullText = currentIndex;
                const targetEndInFullText = currentIndex + textToFind.length;
                let currentPosInFullText = 0;

                for (const seg of segments) {
                    const segStartInFullText = currentPosInFullText;
                    const segTextLength = seg.text.length;
                    const segEndInFullText = segStartInFullText + segTextLength;

                    if (startIndex === -1 && targetStartInFullText >= segStartInFullText && targetStartInFullText < segEndInFullText) {
                        startIndex = seg.start + (targetStartInFullText - segStartInFullText);
                    }
                    if (targetEndInFullText > segStartInFullText && targetEndInFullText <= segEndInFullText) {
                        endIndex = seg.start + (targetEndInFullText - segStartInFullText);
                        break;
                    }
                    currentPosInFullText = segEndInFullText;
                }

                if (startIndex === -1 || endIndex === -1) { // Mapping failed for this instance
                    startIndex = -1; endIndex = -1;
                    // Continue searching from *after* this failed mapping attempt
                    searchStartIndex = currentIndex + 1;
                    foundCount--; // Decrement count as this instance wasn't successfully mapped
                    continue;
                }
                // Successfully mapped
                 return { startIndex, endIndex };
            }
             // Prepare for next search iteration
            searchStartIndex = currentIndex + 1;
        }

        return null; // Instance not found or mapping failed for all attempts
    } catch (error: any) {
        console.error(`Error finding text "${textToFind}" in doc ${documentId}: ${error.message}`);
         if (error.code === 404) throw new UserError(`Document not found while searching text (ID: ${documentId}).`);
         if (error.code === 403) throw new UserError(`Permission denied while searching text in doc (ID: ${documentId}).`);
        throw new Error(`Failed to retrieve doc for text searching: ${error.message}`);
    }

}

// --- Paragraph Boundary Helper ---
// Finds the paragraph containing a given index. Very simplified.
// A robust version needs to understand structural elements better.
export async function getParagraphRange(docs: Docs, documentId: string, indexWithin: number): Promise<{ startIndex: number; endIndex: number } | null> {
try {
const res = await docs.documents.get({
documentId,
// Request paragraph elements and their ranges
fields: 'body(content(startIndex,endIndex,paragraph))',
});

        if (!res.data.body?.content) return null;

        for (const element of res.data.body.content) {
            if (element.paragraph && element.startIndex && element.endIndex) {
                // Check if the provided index falls within this paragraph element's range
                // API ranges are typically [startIndex, endIndex)
                if (indexWithin >= element.startIndex && indexWithin < element.endIndex) {
                    return { startIndex: element.startIndex, endIndex: element.endIndex };
                }
            }
        }
        return null; // Index not found within any paragraph element

    } catch (error: any) {
        console.error(`Error getting paragraph range for index ${indexWithin} in doc ${documentId}: ${error.message}`);
         if (error.code === 404) throw new UserError(`Document not found while finding paragraph range (ID: ${documentId}).`);
         if (error.code === 403) throw new UserError(`Permission denied while finding paragraph range in doc (ID: ${documentId}).`);
        throw new Error(`Failed to retrieve doc for paragraph range finding: ${error.message}`);
    }

}

// --- Style Request Builders ---

export function buildUpdateTextStyleRequest(
startIndex: number,
endIndex: number,
style: TextStyleArgs
): { request: docs_v1.Schema$Request, fields: string[] } | null {
    const textStyle: docs_v1.Schema$TextStyle = {};
const fieldsToUpdate: string[] = [];

    if (style.bold !== undefined) { textStyle.bold = style.bold; fieldsToUpdate.push('bold'); }
    if (style.italic !== undefined) { textStyle.italic = style.italic; fieldsToUpdate.push('italic'); }
    if (style.underline !== undefined) { textStyle.underline = style.underline; fieldsToUpdate.push('underline'); }
    if (style.strikethrough !== undefined) { textStyle.strikethrough = style.strikethrough; fieldsToUpdate.push('strikethrough'); }
    if (style.fontSize !== undefined) { textStyle.fontSize = { magnitude: style.fontSize, unit: 'PT' }; fieldsToUpdate.push('fontSize'); }
    if (style.fontFamily !== undefined) { textStyle.weightedFontFamily = { fontFamily: style.fontFamily }; fieldsToUpdate.push('weightedFontFamily'); }
    if (style.foregroundColor !== undefined) {
        const rgbColor = hexToRgbColor(style.foregroundColor);
        if (!rgbColor) throw new UserError(`Invalid foreground hex color format: ${style.foregroundColor}`);
        textStyle.foregroundColor = { color: { rgbColor: rgbColor } }; fieldsToUpdate.push('foregroundColor');
    }
     if (style.backgroundColor !== undefined) {
        const rgbColor = hexToRgbColor(style.backgroundColor);
        if (!rgbColor) throw new UserError(`Invalid background hex color format: ${style.backgroundColor}`);
        textStyle.backgroundColor = { color: { rgbColor: rgbColor } }; fieldsToUpdate.push('backgroundColor');
    }
    if (style.linkUrl !== undefined) {
        textStyle.link = { url: style.linkUrl }; fieldsToUpdate.push('link');
    }
    // TODO: Handle clearing formatting

    if (fieldsToUpdate.length === 0) return null; // No styles to apply

    const request: docs_v1.Schema$Request = {
        updateTextStyle: {
            range: { startIndex, endIndex },
            textStyle: textStyle,
            fields: fieldsToUpdate.join(','),
        }
    };
    return { request, fields: fieldsToUpdate };

}

export function buildUpdateParagraphStyleRequest(
startIndex: number,
endIndex: number,
style: ParagraphStyleArgs
): { request: docs_v1.Schema$Request, fields: string[] } | null {
    const paragraphStyle: docs_v1.Schema$ParagraphStyle = {};
const fieldsToUpdate: string[] = [];

    if (style.alignment !== undefined) { paragraphStyle.alignment = style.alignment; fieldsToUpdate.push('alignment'); }
    if (style.indentStart !== undefined) { paragraphStyle.indentStart = { magnitude: style.indentStart, unit: 'PT' }; fieldsToUpdate.push('indentStart'); }
    if (style.indentEnd !== undefined) { paragraphStyle.indentEnd = { magnitude: style.indentEnd, unit: 'PT' }; fieldsToUpdate.push('indentEnd'); }
    if (style.spaceAbove !== undefined) { paragraphStyle.spaceAbove = { magnitude: style.spaceAbove, unit: 'PT' }; fieldsToUpdate.push('spaceAbove'); }
    if (style.spaceBelow !== undefined) { paragraphStyle.spaceBelow = { magnitude: style.spaceBelow, unit: 'PT' }; fieldsToUpdate.push('spaceBelow'); }
    if (style.namedStyleType !== undefined) { paragraphStyle.namedStyleType = style.namedStyleType; fieldsToUpdate.push('namedStyleType'); }
    if (style.keepWithNext !== undefined) { paragraphStyle.keepWithNext = style.keepWithNext; fieldsToUpdate.push('keepWithNext'); }
     // TODO: Handle borders, clearing formatting

    if (fieldsToUpdate.length === 0) return null; // No styles to apply

     const request: docs_v1.Schema$Request = {
        updateParagraphStyle: {
            range: { startIndex, endIndex },
            paragraphStyle: paragraphStyle,
            fields: fieldsToUpdate.join(','),
        }
    };
     return { request, fields: fieldsToUpdate };

}

// --- Specific Feature Helpers ---

export async function createTable(docs: Docs, documentId: string, rows: number, columns: number, index: number): Promise<docs_v1.Schema$BatchUpdateDocumentResponse> {
    if (rows < 1 || columns < 1) {
        throw new UserError("Table must have at least 1 row and 1 column.");
    }
    const request: docs_v1.Schema$Request = {
insertTable: {
location: { index },
rows: rows,
columns: columns,
}
};
return executeBatchUpdate(docs, documentId, [request]);
}

export async function insertText(docs: Docs, documentId: string, text: string, index: number): Promise<docs_v1.Schema$BatchUpdateDocumentResponse> {
    if (!text) return {}; // Nothing to insert
    const request: docs_v1.Schema$Request = {
insertText: {
location: { index },
text: text,
}
};
return executeBatchUpdate(docs, documentId, [request]);
}

// --- Complex / Stubbed Helpers ---

export async function findParagraphsMatchingStyle(
docs: Docs,
documentId: string,
styleCriteria: any // Define a proper type for criteria (e.g., { fontFamily: 'Arial', bold: true })
): Promise<{ startIndex: number; endIndex: number }[]> {
// TODO: Implement logic
// 1. Get document content with paragraph elements and their styles.
// 2. Iterate through paragraphs.
// 3. For each paragraph, check if its computed style matches the criteria.
// 4. Return ranges of matching paragraphs.
console.warn("findParagraphsMatchingStyle is not implemented.");
throw new NotImplementedError("Finding paragraphs by style criteria is not yet implemented.");
// return [];
}

export async function detectAndFormatLists(
docs: Docs,
documentId: string,
startIndex?: number,
endIndex?: number
): Promise<docs_v1.Schema$BatchUpdateDocumentResponse> {
// TODO: Implement complex logic
// 1. Get document content (paragraphs, text runs) in the specified range (or whole doc).
// 2. Iterate through paragraphs.
// 3. Identify sequences of paragraphs starting with list-like markers (e.g., "-", "\*", "1.", "a)").
// 4. Determine nesting levels based on indentation or marker patterns.
// 5. Generate CreateParagraphBulletsRequests for the identified sequences.
// 6. Potentially delete the original marker text.
// 7. Execute the batch update.
console.warn("detectAndFormatLists is not implemented.");
throw new NotImplementedError("Automatic list detection and formatting is not yet implemented.");
// return {};
}

export async function addCommentHelper(docs: Docs, documentId: string, text: string, startIndex: number, endIndex: number): Promise<void> {
// NOTE: Adding comments typically requires the Google Drive API v3 and different scopes!
// 'https://www.googleapis.com/auth/drive' or more specific comment scopes.
// This helper is a placeholder assuming Drive API client (`drive`) is available and authorized.
/_
const drive = google.drive({version: 'v3', auth: authClient}); // Assuming authClient is available
await drive.comments.create({
fileId: documentId,
requestBody: {
content: text,
anchor: JSON.stringify({ // Anchor format might need verification
'type': 'workbook#textAnchor', // Or appropriate type for Docs
'refs': [{
'docRevisionId': 'head', // Or specific revision
'range': {
'start': startIndex,
'end': endIndex,
}
}]
})
},
fields: 'id'
});
_/
console.warn("addCommentHelper requires Google Drive API and is not implemented.");
throw new NotImplementedError("Adding comments requires Drive API setup and is not yet implemented.");
}

// Add more helpers as needed...
Use code with caution.
TypeScript 3. Updated File: src/server.ts (Replace the entire content with this)
// src/server.ts
import { FastMCP, UserError } from 'fastmcp';
import { z } from 'zod';
import { google, docs_v1 } from 'googleapis';
import { authorize } from './auth.js';
import { OAuth2Client } from 'google-auth-library';

// Import types and helpers
import {
DocumentIdParameter,
RangeParameters,
OptionalRangeParameters,
TextFindParameter,
TextStyleParameters,
TextStyleArgs,
ParagraphStyleParameters,
ParagraphStyleArgs,
ApplyTextStyleToolParameters, ApplyTextStyleToolArgs,
ApplyParagraphStyleToolParameters, ApplyParagraphStyleToolArgs,
NotImplementedError
} from './types.js';
import \* as GDocsHelpers from './googleDocsApiHelpers.js';

let authClient: OAuth2Client | null = null;
let googleDocs: docs_v1.Docs | null = null;

// --- Initialization ---
async function initializeGoogleClient() {
if (googleDocs) return { authClient, googleDocs };
if (!authClient) { // Check authClient instead of googleDocs to allow re-attempt
try {
console.error("Attempting to authorize Google API client...");
const client = await authorize();
authClient = client; // Assign client here
googleDocs = google.docs({ version: 'v1', auth: authClient });
console.error("Google API client authorized successfully.");
} catch (error) {
console.error("FATAL: Failed to initialize Google API client:", error);
authClient = null; // Reset on failure
googleDocs = null;
// Decide if server should exit or just fail tools
throw new Error("Google client initialization failed. Cannot start server tools.");
}
}
// Ensure googleDocs is set if authClient is valid
if (authClient && !googleDocs) {
googleDocs = google.docs({ version: 'v1', auth: authClient });
}

if (!googleDocs) {
throw new Error("Google Docs client could not be initialized.");
}

return { authClient, googleDocs };
}

const server = new FastMCP({
name: 'Ultimate Google Docs MCP Server',
version: '2.0.0', // Version bump!
description: 'Provides advanced tools for reading, editing, formatting, and managing Google Documents.'
});

// --- Helper to get Docs client within tools ---
async function getDocsClient() {
const { googleDocs: docs } = await initializeGoogleClient();
if (!docs) {
throw new UserError("Google Docs client is not initialized. Authentication might have failed during startup or lost connection.");
}
return docs;
}

// === TOOL DEFINITIONS ===

// --- Foundational Tools ---

server.addTool({
name: 'readGoogleDoc',
description: 'Reads the content of a specific Google Document, optionally returning structured data.',
parameters: DocumentIdParameter.extend({
format: z.enum(['text', 'json', 'markdown']).optional().default('text')
.describe("Output format: 'text' (plain text, possibly truncated), 'json' (raw API structure, complex), 'markdown' (experimental conversion).")
}),
execute: async (args, { log }) => {
const docs = await getDocsClient();
log.info(`Reading Google Doc: ${args.documentId}, Format: ${args.format}`);

    try {
        const fields = args.format === 'json' || args.format === 'markdown'
            ? '*' // Get everything for structure analysis
            : 'body(content(paragraph(elements(textRun(content)))))'; // Just text content

        const res = await docs.documents.get({
            documentId: args.documentId,
            fields: fields,
        });
        log.info(`Fetched doc: ${args.documentId}`);

        if (args.format === 'json') {
            return JSON.stringify(res.data, null, 2); // Return raw structure
        }

        if (args.format === 'markdown') {
            // TODO: Implement Markdown conversion logic (complex)
            log.warn("Markdown conversion is not implemented yet.");
             throw new NotImplementedError("Markdown output format is not yet implemented.");
            // return convertDocsJsonToMarkdown(res.data);
        }

        // Default: Text format
        let textContent = '';
        res.data.body?.content?.forEach(element => {
            element.paragraph?.elements?.forEach(pe => {
            textContent += pe.textRun?.content || '';
            });
        });

        if (!textContent.trim()) return "Document found, but appears empty.";

        // Basic truncation for text mode
        const maxLength = 4000; // Increased limit
        const truncatedContent = textContent.length > maxLength ? textContent.substring(0, maxLength) + `... [truncated ${textContent.length} chars]` : textContent;
        return `Content:\n---\n${truncatedContent}`;

    } catch (error: any) {
         log.error(`Error reading doc ${args.documentId}: ${error.message || error}`);
         // Handle errors thrown by helpers or API directly
         if (error instanceof UserError) throw error;
         if (error instanceof NotImplementedError) throw error;
         // Generic fallback for API errors not caught by helpers
          if (error.code === 404) throw new UserError(`Doc not found (ID: ${args.documentId}).`);
          if (error.code === 403) throw new UserError(`Permission denied for doc (ID: ${args.documentId}).`);
         throw new UserError(`Failed to read doc: ${error.message || 'Unknown error'}`);
    }

},
});

server.addTool({
name: 'appendToGoogleDoc',
description: 'Appends text to the very end of a specific Google Document.',
parameters: DocumentIdParameter.extend({
textToAppend: z.string().min(1).describe('The text to add to the end.'),
addNewlineIfNeeded: z.boolean().optional().default(true).describe("Automatically add a newline before the appended text if the doc doesn't end with one."),
}),
execute: async (args, { log }) => {
const docs = await getDocsClient();
log.info(`Appending to Google Doc: ${args.documentId}`);

    try {
        // Get the current end index
        const docInfo = await docs.documents.get({ documentId: args.documentId, fields: 'body(content(endIndex)),documentStyle(pageSize)' }); // Need content for endIndex
        let endIndex = 1;
        let lastCharIsNewline = false;
        if (docInfo.data.body?.content) {
            const lastElement = docInfo.data.body.content[docInfo.data.body.content.length - 1];
             if (lastElement?.endIndex) {
                endIndex = lastElement.endIndex -1; // Insert *before* the final newline of the doc typically
                // Crude check for last character (better check would involve reading last text run)
                 // const lastTextRun = ... find last text run ...
                 // if (lastTextRun?.content?.endsWith('\n')) lastCharIsNewline = true;
            }
        }
        // Simpler approach: Always assume insertion is needed unless explicitly told not to add newline
        const textToInsert = (args.addNewlineIfNeeded && endIndex > 1 ? '\n' : '') + args.textToAppend;

        if (!textToInsert) return "Nothing to append.";

        const request: docs_v1.Schema$Request = { insertText: { location: { index: endIndex }, text: textToInsert } };
        await GDocsHelpers.executeBatchUpdate(docs, args.documentId, [request]);

        log.info(`Successfully appended to doc: ${args.documentId}`);
        return `Successfully appended text to document ${args.documentId}.`;
    } catch (error: any) {
         log.error(`Error appending to doc ${args.documentId}: ${error.message || error}`);
         if (error instanceof UserError) throw error;
         if (error instanceof NotImplementedError) throw error;
         throw new UserError(`Failed to append to doc: ${error.message || 'Unknown error'}`);
    }

},
});

server.addTool({
name: 'insertText',
description: 'Inserts text at a specific index within the document body.',
parameters: DocumentIdParameter.extend({
textToInsert: z.string().min(1).describe('The text to insert.'),
index: z.number().int().min(1).describe('The index (1-based) where the text should be inserted.'),
}),
execute: async (args, { log }) => {
const docs = await getDocsClient();
log.info(`Inserting text in doc ${args.documentId} at index ${args.index}`);
try {
await GDocsHelpers.insertText(docs, args.documentId, args.textToInsert, args.index);
return `Successfully inserted text at index ${args.index}.`;
} catch (error: any) {
log.error(`Error inserting text in doc ${args.documentId}: ${error.message || error}`);
if (error instanceof UserError) throw error;
throw new UserError(`Failed to insert text: ${error.message || 'Unknown error'}`);
}
}
});

server.addTool({
name: 'deleteRange',
description: 'Deletes content within a specified range (start index inclusive, end index exclusive).',
parameters: DocumentIdParameter.extend(RangeParameters.shape), // Use shape to avoid refine conflict if needed
execute: async (args, { log }) => {
const docs = await getDocsClient();
log.info(`Deleting range ${args.startIndex}-${args.endIndex} in doc ${args.documentId}`);
if (args.endIndex <= args.startIndex) {
throw new UserError("End index must be greater than start index for deletion.");
}
try {
const request: docs_v1.Schema$Request = {
                deleteContentRange: {
                    range: { startIndex: args.startIndex, endIndex: args.endIndex }
                }
            };
            await GDocsHelpers.executeBatchUpdate(docs, args.documentId, [request]);
            return `Successfully deleted content in range ${args.startIndex}-${args.endIndex}.`;
        } catch (error: any) {
            log.error(`Error deleting range in doc ${args.documentId}: ${error.message || error}`);
            if (error instanceof UserError) throw error;
            throw new UserError(`Failed to delete range: ${error.message || 'Unknown error'}`);
}
}
});

// --- Advanced Formatting & Styling Tools ---

server.addTool({
name: 'applyTextStyle',
description: 'Applies character-level formatting (bold, color, font, etc.) to a specific range or found text.',
parameters: ApplyTextStyleToolParameters,
execute: async (args: ApplyTextStyleToolArgs, { log }) => {
const docs = await getDocsClient();
let { startIndex, endIndex } = args.target as any; // Will be updated if target is text

        log.info(`Applying text style in doc ${args.documentId}. Target: ${JSON.stringify(args.target)}, Style: ${JSON.stringify(args.style)}`);

        try {
            // Determine target range
            if ('textToFind' in args.target) {
                const range = await GDocsHelpers.findTextRange(docs, args.documentId, args.target.textToFind, args.target.matchInstance);
                if (!range) {
                    throw new UserError(`Could not find instance ${args.target.matchInstance} of text "${args.target.textToFind}".`);
                }
                startIndex = range.startIndex;
                endIndex = range.endIndex;
                log.info(`Found text "${args.target.textToFind}" (instance ${args.target.matchInstance}) at range ${startIndex}-${endIndex}`);
            }

            if (startIndex === undefined || endIndex === undefined) {
                 throw new UserError("Target range could not be determined.");
            }
             if (endIndex <= startIndex) {
                 throw new UserError("End index must be greater than start index for styling.");
            }

            // Build the request
            const requestInfo = GDocsHelpers.buildUpdateTextStyleRequest(startIndex, endIndex, args.style);
            if (!requestInfo) {
                 return "No valid text styling options were provided.";
            }

            await GDocsHelpers.executeBatchUpdate(docs, args.documentId, [requestInfo.request]);
            return `Successfully applied text style (${requestInfo.fields.join(', ')}) to range ${startIndex}-${endIndex}.`;

        } catch (error: any) {
            log.error(`Error applying text style in doc ${args.documentId}: ${error.message || error}`);
            if (error instanceof UserError) throw error;
            if (error instanceof NotImplementedError) throw error; // Should not happen here
            throw new UserError(`Failed to apply text style: ${error.message || 'Unknown error'}`);
        }
    }

});

server.addTool({
name: 'applyParagraphStyle',
description: 'Applies paragraph-level formatting (alignment, spacing, named styles like Heading 1) to the paragraph(s) containing specific text, an index, or a range.',
parameters: ApplyParagraphStyleToolParameters,
execute: async (args: ApplyParagraphStyleToolArgs, { log }) => {
const docs = await getDocsClient();
let { startIndex, endIndex } = args.target as any; // Will be updated

        log.info(`Applying paragraph style in doc ${args.documentId}. Target: ${JSON.stringify(args.target)}, Style: ${JSON.stringify(args.style)}`);

        try {
             // Determine target paragraph range
             let targetIndexForLookup: number | undefined;

             if ('textToFind' in args.target) {
                const range = await GDocsHelpers.findTextRange(docs, args.documentId, args.target.textToFind, args.target.matchInstance);
                if (!range) {
                    throw new UserError(`Could not find instance ${args.target.matchInstance} of text "${args.target.textToFind}" to locate paragraph.`);
                }
                targetIndexForLookup = range.startIndex; // Use the start index of found text
                log.info(`Found text "${args.target.textToFind}" at index ${targetIndexForLookup} to locate paragraph.`);
            } else if ('indexWithinParagraph' in args.target) {
                 targetIndexForLookup = args.target.indexWithinParagraph;
            } else if ('startIndex' in args.target && 'endIndex' in args.target) {
                 // User provided a range, assume it's the paragraph range
                 startIndex = args.target.startIndex;
                 endIndex = args.target.endIndex;
                 log.info(`Using provided range ${startIndex}-${endIndex} for paragraph style.`);
            }

            // If we need to find the paragraph boundaries based on an index within it
            if (targetIndexForLookup !== undefined && (startIndex === undefined || endIndex === undefined)) {
                 const paragraphRange = await GDocsHelpers.getParagraphRange(docs, args.documentId, targetIndexForLookup);
                 if (!paragraphRange) {
                     throw new UserError(`Could not determine paragraph boundaries containing index ${targetIndexForLookup}.`);
                 }
                 startIndex = paragraphRange.startIndex;
                 endIndex = paragraphRange.endIndex;
                 log.info(`Determined paragraph range as ${startIndex}-${endIndex} based on index ${targetIndexForLookup}.`);
            }


            if (startIndex === undefined || endIndex === undefined) {
                 throw new UserError("Target paragraph range could not be determined.");
            }
             if (endIndex <= startIndex) {
                 throw new UserError("Paragraph end index must be greater than start index for styling.");
            }

            // Build the request
            const requestInfo = GDocsHelpers.buildUpdateParagraphStyleRequest(startIndex, endIndex, args.style);
             if (!requestInfo) {
                 return "No valid paragraph styling options were provided.";
            }

            await GDocsHelpers.executeBatchUpdate(docs, args.documentId, [requestInfo.request]);
            return `Successfully applied paragraph style (${requestInfo.fields.join(', ')}) to range ${startIndex}-${endIndex}.`;

        } catch (error: any) {
            log.error(`Error applying paragraph style in doc ${args.documentId}: ${error.message || error}`);
            if (error instanceof UserError) throw error;
            if (error instanceof NotImplementedError) throw error;
            throw new UserError(`Failed to apply paragraph style: ${error.message || 'Unknown error'}`);
        }
    }

});

// --- Structure & Content Tools ---

server.addTool({
name: 'insertTable',
description: 'Inserts a new table with the specified dimensions at a given index.',
parameters: DocumentIdParameter.extend({
rows: z.number().int().min(1).describe('Number of rows for the new table.'),
columns: z.number().int().min(1).describe('Number of columns for the new table.'),
index: z.number().int().min(1).describe('The index (1-based) where the table should be inserted.'),
}),
execute: async (args, { log }) => {
const docs = await getDocsClient();
log.info(`Inserting ${args.rows}x${args.columns} table in doc ${args.documentId} at index ${args.index}`);
try {
await GDocsHelpers.createTable(docs, args.documentId, args.rows, args.columns, args.index);
// The API response contains info about the created table, but might be too complex to return here.
return `Successfully inserted a ${args.rows}x${args.columns} table at index ${args.index}.`;
} catch (error: any) {
log.error(`Error inserting table in doc ${args.documentId}: ${error.message || error}`);
if (error instanceof UserError) throw error;
throw new UserError(`Failed to insert table: ${error.message || 'Unknown error'}`);
}
}
});

server.addTool({
name: 'editTableCell',
description: 'Edits the content and/or basic style of a specific table cell. Requires knowing table start index.',
parameters: DocumentIdParameter.extend({
tableStartIndex: z.number().int().min(1).describe("The starting index of the TABLE element itself (tricky to find, may require reading structure first)."),
rowIndex: z.number().int().min(0).describe("Row index (0-based)."),
columnIndex: z.number().int().min(0).describe("Column index (0-based)."),
textContent: z.string().optional().describe("Optional: New text content for the cell. Replaces existing content."),
// Combine basic styles for simplicity here. More advanced cell styling might need separate tools.
textStyle: TextStyleParameters.optional().describe("Optional: Text styles to apply."),
paragraphStyle: ParagraphStyleParameters.optional().describe("Optional: Paragraph styles (like alignment) to apply."),
// cellBackgroundColor: z.string().optional()... // Cell-specific styles are complex
}),
execute: async (args, { log }) => {
const docs = await getDocsClient();
log.info(`Editing cell (${args.rowIndex}, ${args.columnIndex}) in table starting at ${args.tableStartIndex}, doc ${args.documentId}`);

        // TODO: Implement complex logic
        // 1. Find the cell's content range based on tableStartIndex, rowIndex, columnIndex. This is NON-TRIVIAL.
        //    Requires getting the document, finding the table element, iterating through rows/cells to calculate indices.
        // 2. If textContent is provided, generate a DeleteContentRange request for the cell's current content.
        // 3. Generate an InsertText request for the new textContent at the cell's start index.
        // 4. If textStyle is provided, generate UpdateTextStyle requests for the new text range.
        // 5. If paragraphStyle is provided, generate UpdateParagraphStyle requests for the cell's paragraph range.
        // 6. Execute batch update.

        log.error("editTableCell is not implemented due to complexity of finding cell indices.");
        throw new NotImplementedError("Editing table cells is complex and not yet implemented.");
        // return `Edit request for cell (${args.rowIndex}, ${args.columnIndex}) submitted (Not Implemented).`;
    }

});

server.addTool({
name: 'insertPageBreak',
description: 'Inserts a page break at the specified index.',
parameters: DocumentIdParameter.extend({
index: z.number().int().min(1).describe('The index (1-based) where the page break should be inserted.'),
}),
execute: async (args, { log }) => {
const docs = await getDocsClient();
log.info(`Inserting page break in doc ${args.documentId} at index ${args.index}`);
try {
const request: docs_v1.Schema$Request = {
insertPageBreak: {
location: { index: args.index }
}
};
await GDocsHelpers.executeBatchUpdate(docs, args.documentId, [request]);
return `Successfully inserted page break at index ${args.index}.`;
} catch (error: any) {
log.error(`Error inserting page break in doc ${args.documentId}: ${error.message || error}`);
if (error instanceof UserError) throw error;
throw new UserError(`Failed to insert page break: ${error.message || 'Unknown error'}`);
}
}
});

// --- Intelligent Assistance Tools (Examples/Stubs) ---

server.addTool({
name: 'fixListFormatting',
description: 'EXPERIMENTAL: Attempts to detect paragraphs that look like lists (e.g., starting with -, \*, 1.) and convert them to proper Google Docs bulleted or numbered lists. Best used on specific sections.',
parameters: DocumentIdParameter.extend({
// Optional range to limit the scope, otherwise scans whole doc (potentially slow/risky)
range: OptionalRangeParameters.optional().describe("Optional: Limit the fixing process to a specific range.")
}),
execute: async (args, { log }) => {
const docs = await getDocsClient();
log.warn(`Executing EXPERIMENTAL fixListFormatting for doc ${args.documentId}. Range: ${JSON.stringify(args.range)}`);
try {
await GDocsHelpers.detectAndFormatLists(docs, args.documentId, args.range?.startIndex, args.range?.endIndex);
return `Attempted to fix list formatting. Please review the document for accuracy.`;
} catch (error: any) {
log.error(`Error fixing list formatting in doc ${args.documentId}: ${error.message || error}`);
if (error instanceof UserError) throw error;
if (error instanceof NotImplementedError) throw error; // Expected if helper not implemented
throw new UserError(`Failed to fix list formatting: ${error.message || 'Unknown error'}`);
}
}
});

server.addTool({
name: 'addComment',
description: 'Adds a comment anchored to a specific text range. REQUIRES DRIVE API SCOPES/SETUP.',
parameters: DocumentIdParameter.extend(RangeParameters.shape).extend({
commentText: z.string().min(1).describe("The content of the comment."),
}),
execute: async (args, { log }) => {
log.info(`Attempting to add comment "${args.commentText}" to range ${args.startIndex}-${args.endIndex} in doc ${args.documentId}`);
// Requires Drive API client and appropriate scopes.
// const { authClient } = await initializeGoogleClient(); // Get auth client if needed
// if (!authClient) throw new UserError("Authentication client not available for Drive API.");
try {
// await GDocsHelpers.addCommentHelper(driveClient, args.documentId, args.commentText, args.startIndex, args.endIndex);
log.error("addComment requires Drive API setup which is not implemented.");
throw new NotImplementedError("Adding comments requires Drive API setup and is not yet implemented in this server.");
// return `Comment added to range ${args.startIndex}-${args.endIndex}.`;
} catch (error: any) {
log.error(`Error adding comment in doc ${args.documentId}: ${error.message || error}`);
if (error instanceof UserError) throw error;
if (error instanceof NotImplementedError) throw error;
throw new UserError(`Failed to add comment: ${error.message || 'Unknown error'}`);
}
}
});

// --- Add Stubs for other advanced features ---
// (findElement, getDocumentMetadata, replaceText, list management, image handling, section breaks, footnotes, etc.)
// Example Stub:
server.addTool({
name: 'findElement',
description: 'Finds elements (paragraphs, tables, etc.) based on various criteria. (Not Implemented)',
parameters: DocumentIdParameter.extend({
// Define complex query parameters...
textQuery: z.string().optional(),
elementType: z.enum(['paragraph', 'table', 'list', 'image']).optional(),
// styleQuery...
}),
execute: async (args, { log }) => {
log.warn("findElement tool called but is not implemented.");
throw new NotImplementedError("Finding elements by complex criteria is not yet implemented.");
}
});

// --- Server Startup ---
async function startServer() {
try {
await initializeGoogleClient(); // Authorize BEFORE starting listeners
console.error("Starting Ultimate Google Docs MCP server...");

      // Using stdio as before
      const configToUse = {
          transportType: "stdio" as const,
      };
      server.start(configToUse);
      console.error(`MCP Server running using ${configToUse.transportType}. Awaiting client connection...`);

} catch(startError: any) {
console.error("FATAL: Server failed to start:", startError.message || startError);
process.exit(1);
}
}

startServer(); // Removed .catch here, let errors propagate if startup fails critically
Use code with caution.
TypeScript
Phase 2: Step-by-Step Update Instructions
Create src/types.ts:
In your project's src directory, create a new file named types.ts.
Copy the entire content from Phase 1, Section 1 (src/types.ts) into this new file. Save it.
Create src/googleDocsApiHelpers.ts:
In your project's src directory, create another new file named googleDocsApiHelpers.ts.
Copy the entire content from Phase 1, Section 2 (src/googleDocsApiHelpers.ts) into this new file. Save it.
Replace src/server.ts:
Open your existing src/server.ts file.
Delete all of its current content.
Copy the entire content from Phase 1, Section 3 (Updated File: src/server.ts) into the now empty src/server.ts file. Save it.
Check src/auth.ts:
No changes are strictly required unless you plan to implement features needing the Drive API (like comments). For now, leave it as is. If you add Drive features later, you'll need to add Drive API scopes (like https://www.googleapis.com/auth/drive) to the SCOPES array in auth.ts and potentially re-authorize (delete token.json and run the server once).
Install Dependencies (If any were added):
Open your terminal in the project root directory.
Run npm install. (In this case, no new dependencies were added, but it's good practice).
Build the Code:
In your terminal, run the build command:
npm run build
Use code with caution.
Bash
This should compile the new .ts files into JavaScript in the dist directory. Check for any compilation errors in the terminal output. Fix them if necessary (typos, import issues, etc.).
Update mcp_config.json (Optional - Check Path):
The command to run the server likely hasn't changed (node /path/to/your/project/dist/server.js). Double-check that the path in your Claude Desktop mcp_config.json still correctly points to the compiled dist/server.js file.
Re-authorize (If Scopes Changed):
If you did change scopes in auth.ts (not required by the code provided), you must delete the token.json file in your project root.
Run the server manually once to go through the Google authorization flow again:
node ./dist/server.js
Use code with caution.
Bash
Follow the on-screen instructions to authorize in your browser and paste the code back into the terminal.
Update Documentation (README.md / docs/index.html):
This is crucial! Your documentation is now outdated.
Edit your README.md and/or docs/index.html.
Remove descriptions of old/removed tools (like the original formatText).
Add detailed descriptions and usage examples for the new tools (applyTextStyle, applyParagraphStyle, insertTable, insertText, deleteRange, fixListFormatting, addComment, etc.). Explain their parameters clearly.
Mention which tools are experimental or not fully implemented.
Test Thoroughly:
Restart Claude Desktop (if using it).
Start testing the new tools one by one with specific prompts.
Begin with simple cases (e.g., applying bold using applyTextStyle with text finding).
Test edge cases (text not found, invalid indices, invalid hex colors).
Test the tools that rely on helpers (e.g., applyParagraphStyle which uses getParagraphRange and findTextRange).
Expect the unimplemented tools to return the "Not Implemented" error.
Monitor the terminal where Claude Desktop runs the server (or run it manually) for error messages (console.error logs).
You now have the code structure and implementation examples for a significantly more powerful Google Docs MCP server. Remember that the unimplemented features and complex helpers will require further development effort. Good luck!

```

--------------------------------------------------------------------------------
/pages/pages.md:
--------------------------------------------------------------------------------

```markdown

```

--------------------------------------------------------------------------------
/.repomix/bundles.json:
--------------------------------------------------------------------------------

```json
{
  "bundles": {}
}
```

--------------------------------------------------------------------------------
/index.js:
--------------------------------------------------------------------------------

```javascript
#!/usr/bin/env node

// Entry point for the Google Docs MCP Server
// This imports and runs the compiled server from the dist directory

import './dist/server.js';

```

--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------

```json
// tsconfig.json
{
    "compilerOptions": {
      "target": "ES2022",
      "module": "NodeNext",
      "moduleResolution": "NodeNext",
      "outDir": "./dist",
      "rootDir": "./src",
      "strict": true,
      "esModuleInterop": true,
      "skipLibCheck": true,
      "forceConsistentCasingInFileNames": true,
      "resolveJsonModule": true
    },
    "include": ["src/**/*"],
    "exclude": ["node_modules"]
  }
```

--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------

```json
{
  "name": "mcp-googledocs-server",
  "version": "1.0.0",
  "type": "module",
  "main": "index.js",
  "scripts": {
    "test": "node --test tests/",
    "build": "tsc"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": "",
  "dependencies": {
    "fastmcp": "^1.21.0",
    "google-auth-library": "^9.15.1",
    "googleapis": "^148.0.0",
    "zod": "^3.24.2"
  },
  "devDependencies": {
    "@types/node": "^22.14.1",
    "tsx": "^4.19.3",
    "typescript": "^5.8.3"
  }
}

```

--------------------------------------------------------------------------------
/tests/types.test.js:
--------------------------------------------------------------------------------

```javascript
// tests/types.test.js
import { hexToRgbColor, validateHexColor } from '../dist/types.js';
import assert from 'node:assert';
import { describe, it } from 'node:test';

describe('Color Validation and Conversion', () => {
  // Test hypothesis 3: Hex color validation and conversion

  describe('validateHexColor', () => {
    it('should validate correct hex colors with hash', () => {
      assert.strictEqual(validateHexColor('#FF0000'), true); // 6 digits red
      assert.strictEqual(validateHexColor('#F00'), true);    // 3 digits red
      assert.strictEqual(validateHexColor('#00FF00'), true); // 6 digits green
      assert.strictEqual(validateHexColor('#0F0'), true);    // 3 digits green
    });

    it('should validate correct hex colors without hash', () => {
      assert.strictEqual(validateHexColor('FF0000'), true);  // 6 digits red
      assert.strictEqual(validateHexColor('F00'), true);     // 3 digits red
      assert.strictEqual(validateHexColor('00FF00'), true);  // 6 digits green
      assert.strictEqual(validateHexColor('0F0'), true);     // 3 digits green
    });

    it('should reject invalid hex colors', () => {
      assert.strictEqual(validateHexColor(''), false);        // Empty
      assert.strictEqual(validateHexColor('#XYZ'), false);    // Invalid characters
      assert.strictEqual(validateHexColor('#12345'), false);  // Invalid length (5)
      assert.strictEqual(validateHexColor('#1234567'), false);// Invalid length (7)
      assert.strictEqual(validateHexColor('invalid'), false); // Not a hex color
      assert.strictEqual(validateHexColor('#12'), false);     // Too short
    });
  });

  describe('hexToRgbColor', () => {
    it('should convert 6-digit hex colors with hash correctly', () => {
      const result = hexToRgbColor('#FF0000');
      assert.deepStrictEqual(result, { red: 1, green: 0, blue: 0 }); // Red
      
      const resultGreen = hexToRgbColor('#00FF00');
      assert.deepStrictEqual(resultGreen, { red: 0, green: 1, blue: 0 }); // Green
      
      const resultBlue = hexToRgbColor('#0000FF');
      assert.deepStrictEqual(resultBlue, { red: 0, green: 0, blue: 1 }); // Blue
      
      const resultPurple = hexToRgbColor('#800080');
      assert.deepStrictEqual(resultPurple, { red: 0.5019607843137255, green: 0, blue: 0.5019607843137255 }); // Purple
    });

    it('should convert 3-digit hex colors correctly', () => {
      const result = hexToRgbColor('#F00');
      assert.deepStrictEqual(result, { red: 1, green: 0, blue: 0 }); // Red from shorthand
      
      const resultWhite = hexToRgbColor('#FFF');
      assert.deepStrictEqual(resultWhite, { red: 1, green: 1, blue: 1 }); // White from shorthand
    });

    it('should convert hex colors without hash correctly', () => {
      const result = hexToRgbColor('FF0000');
      assert.deepStrictEqual(result, { red: 1, green: 0, blue: 0 }); // Red without hash
    });

    it('should return null for invalid hex colors', () => {
      assert.strictEqual(hexToRgbColor(''), null);        // Empty
      assert.strictEqual(hexToRgbColor('#XYZ'), null);    // Invalid characters
      assert.strictEqual(hexToRgbColor('#12345'), null);  // Invalid length
      assert.strictEqual(hexToRgbColor('invalid'), null); // Not a hex color
    });
  });
});
```

--------------------------------------------------------------------------------
/src/auth.ts:
--------------------------------------------------------------------------------

```typescript
// src/auth.ts
import { google } from 'googleapis';
import { OAuth2Client } from 'google-auth-library';
import * as fs from 'fs/promises';
import * as path from 'path';
import * as readline from 'readline/promises';
import { fileURLToPath } from 'url';

// --- Calculate paths relative to this script file (ESM way) ---
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const projectRootDir = path.resolve(__dirname, '..');

const TOKEN_PATH = path.join(projectRootDir, 'token.json');
const CREDENTIALS_PATH = path.join(projectRootDir, 'credentials.json');
// --- End of path calculation ---

const SCOPES = [
  'https://www.googleapis.com/auth/documents',
  'https://www.googleapis.com/auth/drive' // Full Drive access for listing, searching, and document discovery
];

async function loadSavedCredentialsIfExist(): Promise<OAuth2Client | null> {
  try {
    const content = await fs.readFile(TOKEN_PATH);
    const credentials = JSON.parse(content.toString());
    const { client_secret, client_id, redirect_uris } = await loadClientSecrets();
    const client = new google.auth.OAuth2(client_id, client_secret, redirect_uris?.[0]);
    client.setCredentials(credentials);
    return client;
  } catch (err) {
    return null;
  }
}

async function loadClientSecrets() {
  const content = await fs.readFile(CREDENTIALS_PATH);
  const keys = JSON.parse(content.toString());
  const key = keys.installed || keys.web;
   if (!key) throw new Error("Could not find client secrets in credentials.json.");
  return {
      client_id: key.client_id,
      client_secret: key.client_secret,
      redirect_uris: key.redirect_uris || ['http://localhost:3000/'], // Default for web clients
      client_type: keys.web ? 'web' : 'installed'
  };
}

async function saveCredentials(client: OAuth2Client): Promise<void> {
  const { client_secret, client_id } = await loadClientSecrets();
  const payload = JSON.stringify({
    type: 'authorized_user',
    client_id: client_id,
    client_secret: client_secret,
    refresh_token: client.credentials.refresh_token,
  });
  await fs.writeFile(TOKEN_PATH, payload);
  console.error('Token stored to', TOKEN_PATH);
}

async function authenticate(): Promise<OAuth2Client> {
  const { client_secret, client_id, redirect_uris, client_type } = await loadClientSecrets();
  // For web clients, use the configured redirect URI; for desktop clients, use 'urn:ietf:wg:oauth:2.0:oob'
  const redirectUri = client_type === 'web' ? redirect_uris[0] : 'urn:ietf:wg:oauth:2.0:oob';
  console.error(`DEBUG: Using redirect URI: ${redirectUri}`);
  console.error(`DEBUG: Client type: ${client_type}`);
  const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirectUri);

  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });

  const authorizeUrl = oAuth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES.join(' '),
  });

  console.error('DEBUG: Generated auth URL:', authorizeUrl);
  console.error('Authorize this app by visiting this url:', authorizeUrl);
  const code = await rl.question('Enter the code from that page here: ');
  rl.close();

  try {
    const { tokens } = await oAuth2Client.getToken(code);
    oAuth2Client.setCredentials(tokens);
    if (tokens.refresh_token) { // Save only if we got a refresh token
         await saveCredentials(oAuth2Client);
    } else {
         console.error("Did not receive refresh token. Token might expire.");
    }
    console.error('Authentication successful!');
    return oAuth2Client;
  } catch (err) {
    console.error('Error retrieving access token', err);
    throw new Error('Authentication failed');
  }
}

export async function authorize(): Promise<OAuth2Client> {
  let client = await loadSavedCredentialsIfExist();
  if (client) {
    // Optional: Add token refresh logic here if needed, though library often handles it.
    console.error('Using saved credentials.');
    return client;
  }
  console.error('Starting authentication flow...');
  client = await authenticate();
  return client;
}

```

--------------------------------------------------------------------------------
/tests/helpers.test.js:
--------------------------------------------------------------------------------

```javascript
// tests/helpers.test.js
import { findTextRange } from '../dist/googleDocsApiHelpers.js';
import assert from 'node:assert';
import { describe, it, mock } from 'node:test';

describe('Text Range Finding', () => {
  // Test hypothesis 1: Text range finding works correctly
  
  describe('findTextRange', () => {
    it('should find text within a single text run correctly', async () => {
      // Mock the docs.documents.get method to return a predefined structure
      const mockDocs = {
        documents: {
          get: mock.fn(async () => ({
            data: {
              body: {
                content: [
                  {
                    paragraph: {
                      elements: [
                        {
                          startIndex: 1,
                          endIndex: 25,
                          textRun: {
                            content: 'This is a test sentence.'
                          }
                        }
                      ]
                    }
                  }
                ]
              }
            }
          }))
        }
      };

      // Test finding "test" in the sample text
      const result = await findTextRange(mockDocs, 'doc123', 'test', 1);
      assert.deepStrictEqual(result, { startIndex: 11, endIndex: 15 });
      
      // Verify the docs.documents.get was called with the right parameters
      assert.strictEqual(mockDocs.documents.get.mock.calls.length, 1);
      assert.deepStrictEqual(
        mockDocs.documents.get.mock.calls[0].arguments[0], 
        {
          documentId: 'doc123',
          fields: 'body(content(paragraph(elements(startIndex,endIndex,textRun(content)))))'
        }
      );
    });
    
    it('should find the nth instance of text correctly', async () => {
      // Mock with a document that has repeated text
      const mockDocs = {
        documents: {
          get: mock.fn(async () => ({
            data: {
              body: {
                content: [
                  {
                    paragraph: {
                      elements: [
                        {
                          startIndex: 1,
                          endIndex: 41,
                          textRun: {
                            content: 'Test test test. This is a test sentence.'
                          }
                        }
                      ]
                    }
                  }
                ]
              }
            }
          }))
        }
      };

      // Find the 3rd instance of "test"
      const result = await findTextRange(mockDocs, 'doc123', 'test', 3);
      assert.deepStrictEqual(result, { startIndex: 27, endIndex: 31 });
    });

    it('should return null if text is not found', async () => {
      const mockDocs = {
        documents: {
          get: mock.fn(async () => ({
            data: {
              body: {
                content: [
                  {
                    paragraph: {
                      elements: [
                        {
                          startIndex: 1,
                          endIndex: 25,
                          textRun: {
                            content: 'This is a sample sentence.'
                          }
                        }
                      ]
                    }
                  }
                ]
              }
            }
          }))
        }
      };

      // Try to find text that doesn't exist
      const result = await findTextRange(mockDocs, 'doc123', 'test', 1);
      assert.strictEqual(result, null);
    });

    it('should handle text spanning multiple text runs', async () => {
      const mockDocs = {
        documents: {
          get: mock.fn(async () => ({
            data: {
              body: {
                content: [
                  {
                    paragraph: {
                      elements: [
                        {
                          startIndex: 1,
                          endIndex: 6,
                          textRun: {
                            content: 'This '
                          }
                        },
                        {
                          startIndex: 6,
                          endIndex: 11,
                          textRun: {
                            content: 'is a '
                          }
                        },
                        {
                          startIndex: 11,
                          endIndex: 20,
                          textRun: {
                            content: 'test case'
                          }
                        }
                      ]
                    }
                  }
                ]
              }
            }
          }))
        }
      };

      // Find text that spans runs: "a test"
      const result = await findTextRange(mockDocs, 'doc123', 'a test', 1);
      assert.deepStrictEqual(result, { startIndex: 9, endIndex: 15 });
    });
  });
});
```

--------------------------------------------------------------------------------
/vscode.md:
--------------------------------------------------------------------------------

```markdown
# VS Code Integration Guide

This guide shows you how to integrate the Ultimate Google Docs & Drive MCP Server with VS Code using the MCP extension.

## Prerequisites

Before setting up VS Code integration, make sure you have:

1. **Completed the main setup** - Follow the [README.md](README.md) setup instructions first
2. **VS Code installed** - Download from [code.visualstudio.com](https://code.visualstudio.com/)
3. **Working MCP server** - Verify your server works with Claude Desktop first

## Installation

### Step 1: Install the MCP Extension

1. Open VS Code
2. Go to Extensions (Ctrl+Shift+X / Cmd+Shift+X)
3. Search for "MCP" or "Model Context Protocol"
4. Install the official MCP extension

### Step 2: Configure the MCP Server

1. Open VS Code Settings (Ctrl+, / Cmd+,)
2. Search for "MCP" in settings
3. Find "MCP: Servers" configuration
4. Add a new server configuration:

```json
{
  "google-docs-drive": {
    "command": "node",
    "args": ["${workspaceFolder}/dist/server.js"],
    "env": {
      "NODE_ENV": "production"
    }
  }
}
```

### Step 3: Verify Configuration

1. Open the Command Palette (Ctrl+Shift+P / Cmd+Shift+P)
2. Type "MCP: Restart Servers" and run it
3. Check the Output panel and select "MCP" from the dropdown
4. You should see your server connecting successfully

## Usage

Once configured, you can use the MCP server with AI assistants in VS Code:

### Document Operations

```
"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'"
```

### File Management

```
"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'"
```

### Document Editing

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

## Troubleshooting

### Server Not Starting

1. **Check the path** - Ensure the absolute path in your configuration is correct
2. **Verify build** - Run `npm run build` in your project directory
3. **Check permissions** - Ensure `token.json` and `credentials.json` exist and are readable

### Authentication Issues

1. **Re-authorize** - Delete `token.json` and run the server manually once:
   ```bash
   cd /path/to/your/google-docs-mcp
   node dist/server.js
   ```
2. **Follow the authorization flow** again
3. **Restart VS Code** after successful authorization

### Tool Not Found Errors

1. **Restart MCP servers** using Command Palette
2. **Check server logs** in VS Code Output panel (MCP channel)

## Available Tools

The server provides these tools in VS Code:

### Document Discovery
- `listGoogleDocs` - List documents with filtering
- `searchGoogleDocs` - Search by name/content
- `getRecentGoogleDocs` - Get recently modified docs
- `getDocumentInfo` - Get detailed document metadata

### Document Editing
- `readGoogleDoc` - Read document content
- `appendToGoogleDoc` - Add text to end
- `insertText` - Insert at specific position
- `deleteRange` - Remove content
- `applyTextStyle` - Format text (bold, italic, colors)
- `applyParagraphStyle` - Format paragraphs (alignment, spacing)
- `formatMatchingText` - Find and format text
- `insertTable` - Create tables
- `insertPageBreak` - Add page breaks

### File Management
- `createFolder` - Create new folders
- `listFolderContents` - List folder contents
- `getFolderInfo` - Get folder metadata
- `moveFile` - Move files/folders
- `copyFile` - Copy files/folders
- `renameFile` - Rename files/folders
- `deleteFile` - Delete files/folders
- `createDocument` - Create new documents
- `createFromTemplate` - Create from templates

## Tips for Better Integration

1. **Use specific document IDs** - More reliable than document names
2. **Combine operations** - Create and format documents in single requests
3. **Check tool results** - Review what was actually done before proceeding
4. **Use templates** - Create template documents for consistent formatting

## Security Notes

- The server uses OAuth 2.0 for secure authentication
- Credentials are stored locally in `token.json` and `credentials.json`
- Never share these files or commit them to version control
- The server only has access to your Google Drive, not other Google services

## Example Workflows

### Create a Formatted Report

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

### Organize Project Documents

```
1. "Create a folder called 'Q1 Project' in my Work folder"
2. "Search for all documents containing 'Q1' in the title"
3. "Move the found documents to the Q1 Project folder"
4. "Create a new document called 'Q1 Project Overview' in that folder"
```

This integration brings the full power of Google Docs and Drive management directly into your VS Code workflow!

```

--------------------------------------------------------------------------------
/src/types.ts:
--------------------------------------------------------------------------------

```typescript
// src/types.ts
import { z } from 'zod';
import { docs_v1 } from 'googleapis';

// --- Helper function for hex color validation ---
export const hexColorRegex = /^#?([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/;
export const validateHexColor = (color: string) => hexColorRegex.test(color);

// --- Helper function for Hex to RGB conversion ---
export function hexToRgbColor(hex: string): docs_v1.Schema$RgbColor | null {
if (!hex) return null;
let hexClean = hex.startsWith('#') ? hex.slice(1) : hex;

if (hexClean.length === 3) {
hexClean = hexClean[0] + hexClean[0] + hexClean[1] + hexClean[1] + hexClean[2] + hexClean[2];
}
if (hexClean.length !== 6) return null;
const bigint = parseInt(hexClean, 16);
if (isNaN(bigint)) return null;

const r = ((bigint >> 16) & 255) / 255;
const g = ((bigint >> 8) & 255) / 255;
const b = (bigint & 255) / 255;

return { red: r, green: g, blue: b };
}

// --- Zod Schema Fragments for Reusability ---

export const DocumentIdParameter = z.object({
documentId: z.string().describe('The ID of the Google Document (from the URL).'),
});

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

export const OptionalRangeParameters = z.object({
startIndex: z.number().int().min(1).optional().describe('Optional: The starting index of the text range (inclusive, starts from 1). If omitted, might apply to a found element or whole paragraph.'),
endIndex: z.number().int().min(1).optional().describe('Optional: The ending index of the text range (exclusive). If omitted, might apply to a found element or whole paragraph.'),
}).refine(data => !data.startIndex || !data.endIndex || data.endIndex > data.startIndex, {
message: "If both startIndex and endIndex are provided, endIndex must be greater than startIndex",
path: ["endIndex"],
});

export const TextFindParameter = z.object({
textToFind: z.string().min(1).describe('The exact text string to locate.'),
matchInstance: z.number().int().min(1).optional().default(1).describe('Which instance of the text to target (1st, 2nd, etc.). Defaults to 1.'),
});

// --- Style Parameter Schemas ---

export const TextStyleParameters = z.object({
bold: z.boolean().optional().describe('Apply bold formatting.'),
italic: z.boolean().optional().describe('Apply italic formatting.'),
underline: z.boolean().optional().describe('Apply underline formatting.'),
strikethrough: z.boolean().optional().describe('Apply strikethrough formatting.'),
fontSize: z.number().min(1).optional().describe('Set font size (in points, e.g., 12).'),
fontFamily: z.string().optional().describe('Set font family (e.g., "Arial", "Times New Roman").'),
foregroundColor: z.string()
.refine(validateHexColor, { message: "Invalid hex color format (e.g., #FF0000 or #F00)" })
.optional()
.describe('Set text color using hex format (e.g., "#FF0000").'),
backgroundColor: z.string()
.refine(validateHexColor, { message: "Invalid hex color format (e.g., #00FF00 or #0F0)" })
.optional()
.describe('Set text background color using hex format (e.g., "#FFFF00").'),
linkUrl: z.string().url().optional().describe('Make the text a hyperlink pointing to this URL.'),
// clearDirectFormatting: z.boolean().optional().describe('If true, attempts to clear all direct text formatting within the range before applying new styles.') // Harder to implement perfectly
}).describe("Parameters for character-level text formatting.");

// Subset of TextStyle used for passing to helpers
export type TextStyleArgs = z.infer<typeof TextStyleParameters>;

export const ParagraphStyleParameters = z.object({
alignment: z.enum(['LEFT', 'CENTER', 'RIGHT', 'JUSTIFIED']).optional().describe('Paragraph alignment.'),
indentStart: z.number().min(0).optional().describe('Left indentation in points.'),
indentEnd: z.number().min(0).optional().describe('Right indentation in points.'),
spaceAbove: z.number().min(0).optional().describe('Space before the paragraph in points.'),
spaceBelow: z.number().min(0).optional().describe('Space after the paragraph in points.'),
namedStyleType: z.enum([
'NORMAL_TEXT', 'TITLE', 'SUBTITLE',
'HEADING_1', 'HEADING_2', 'HEADING_3', 'HEADING_4', 'HEADING_5', 'HEADING_6'
]).optional().describe('Apply a built-in named paragraph style (e.g., HEADING_1).'),
keepWithNext: z.boolean().optional().describe('Keep this paragraph together with the next one on the same page.'),
// Borders are more complex, might need separate objects/tools
// clearDirectFormatting: z.boolean().optional().describe('If true, attempts to clear all direct paragraph formatting within the range before applying new styles.') // Harder to implement perfectly
}).describe("Parameters for paragraph-level formatting.");

// Subset of ParagraphStyle used for passing to helpers
export type ParagraphStyleArgs = z.infer<typeof ParagraphStyleParameters>;

// --- Combination Schemas for Tools ---

export const ApplyTextStyleToolParameters = DocumentIdParameter.extend({
// Target EITHER by range OR by finding text
target: z.union([
RangeParameters,
TextFindParameter
]).describe("Specify the target range either by start/end indices or by finding specific text."),
style: TextStyleParameters.refine(
styleArgs => Object.values(styleArgs).some(v => v !== undefined),
{ message: "At least one text style option must be provided." }
).describe("The text styling to apply.")
});
export type ApplyTextStyleToolArgs = z.infer<typeof ApplyTextStyleToolParameters>;

export const ApplyParagraphStyleToolParameters = DocumentIdParameter.extend({
// Target EITHER by range OR by finding text (tool logic needs to find paragraph boundaries)
target: z.union([
RangeParameters, // User provides paragraph start/end (less likely)
TextFindParameter.extend({
applyToContainingParagraph: z.literal(true).default(true).describe("Must be true. Indicates the style applies to the whole paragraph containing the found text.")
}),
z.object({ // Target by specific index within the paragraph
indexWithinParagraph: z.number().int().min(1).describe("An index located anywhere within the target paragraph.")
})
]).describe("Specify the target paragraph either by start/end indices, by finding text within it, or by providing an index within it."),
style: ParagraphStyleParameters.refine(
styleArgs => Object.values(styleArgs).some(v => v !== undefined),
{ message: "At least one paragraph style option must be provided." }
).describe("The paragraph styling to apply.")
});
export type ApplyParagraphStyleToolArgs = z.infer<typeof ApplyParagraphStyleToolParameters>;

// --- Error Class ---
// Use FastMCP's UserError for client-facing issues
// Define a custom error for internal issues if needed
export class NotImplementedError extends Error {
constructor(message = "This feature is not yet implemented.") {
super(message);
this.name = "NotImplementedError";
}
}
```

--------------------------------------------------------------------------------
/SAMPLE_TASKS.md:
--------------------------------------------------------------------------------

```markdown
# 15 Powerful Tasks with the Ultimate Google Docs & Drive MCP Server

This document showcases practical examples of what you can accomplish with the enhanced Google Docs & Drive MCP Server. These examples demonstrate how AI assistants like Claude can perform sophisticated document formatting, structuring, and file management tasks through the MCP interface.

## Document Formatting & Structure Tasks

## 1. Create and Format a Document Header

```
Task: "Create a professional document header for my project proposal."

Steps:
1. Insert the title "Project Proposal: AI Integration Strategy" at the beginning of the document
2. Apply Heading 1 style to the title using applyParagraphStyle
3. Add a horizontal line below the title
4. Insert the date and author information
5. Apply a subtle background color to the header section
```

## 2. Generate and Format a Table of Contents

```
Task: "Create a table of contents for my document based on its headings."

Steps:
1. Find all text with Heading styles (1-3) using findParagraphsMatchingStyle
2. Create a "Table of Contents" section at the beginning of the document
3. Insert each heading with appropriate indentation based on its level
4. Format the TOC entries with page numbers and dotted lines
5. Apply consistent styling to the entire TOC
```

## 3. Structure a Document with Consistent Formatting

```
Task: "Apply consistent formatting throughout my document based on content type."

Steps:
1. Format all section headings with applyParagraphStyle (Heading styles, alignment)
2. Style all bullet points with consistent indentation and formatting
3. Format code samples with monospace font and background color
4. Apply consistent paragraph spacing throughout the document
5. Format all hyperlinks with a consistent color and underline style
```

## 4. Create a Professional Table for Data Presentation

```
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
```

## 5. Prepare a Document for Formal Submission

```
Task: "Format my research paper according to academic guidelines."

Steps:
1. Set the title with centered alignment and appropriate font size
2. Format all headings according to the required style guide
3. Apply double spacing to the main text
4. Insert page numbers with appropriate format
5. Format citations consistently
6. Apply indentation to block quotes
7. Format the bibliography section
```

## 6. Create an Executive Summary with Highlights

```
Task: "Create an executive summary that emphasizes key points from my report."

Steps:
1. Insert a page break and create an "Executive Summary" section
2. Extract and format key points from the document
3. Apply bullet points for clarity
4. Highlight critical figures or statistics in bold
5. Use color to emphasize particularly important points
6. Format the summary with appropriate spacing and margins
```

## 7. Format a Document for Different Audiences

```
Task: "Create two versions of my presentation - one technical and one for executives."

Steps:
1. Duplicate the document content
2. For the technical version:
   - Add detailed technical sections
   - Include code examples with monospace formatting
   - Use technical terminology
3. For the executive version:
   - Emphasize business impact with bold and color
   - Simplify technical concepts
   - Add executive summary
   - Use more visual formatting elements
```

## 8. Create a Response Form with Structured Fields

```
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
```

## 9. Format a Document with Multi-Level Lists

```
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
```

## 10. Prepare a Document with Advanced Layout

```
Task: "Create a newsletter-style document with columns and sections."

Steps:
1. Create a bold, centered title for the newsletter
2. Insert a horizontal line separator
3. Create differently formatted sections for:
   - Main article (left-aligned paragraphs)
   - Sidebar content (indented, smaller text)
   - Highlighted quotes (centered, italic)
4. Insert and format images with captions
5. Add a formatted footer with contact information
6. Apply consistent spacing between sections
```

These examples demonstrate the power and flexibility of the enhanced Google Docs & Drive MCP Server, showcasing how AI assistants can help with sophisticated document formatting, structuring, and comprehensive file management tasks.

## Google Drive Management Tasks

## 11. Organize Project Files Automatically

```
Task: "Set up a complete project structure and organize existing files."

Steps:
1. Create a main project folder using createFolder
2. Create subfolders for different aspects (Documents, Templates, Archive)
3. Search for project-related documents using searchGoogleDocs
4. Move relevant documents to appropriate subfolders with moveFile
5. Create a project index document listing all resources
6. Format the index with links to all project documents
```

## 12. Create Document Templates and Generate Reports

```
Task: "Set up a template system and generate standardized reports."

Steps:
1. Create a Templates folder using createFolder
2. Create template documents with placeholder text ({{DATE}}, {{NAME}}, etc.)
3. Use createFromTemplate to generate new reports from templates
4. Apply text replacements to customize each report
5. Organize generated reports in appropriate folders
6. Create a tracking document listing all generated reports
```

## 13. Archive and Clean Up Old Documents

```
Task: "Archive outdated documents and organize current files."

Steps:
1. Create an Archive folder for old documents using createFolder
2. Use getRecentGoogleDocs to find documents older than 90 days
3. Review and move old documents to Archive using moveFile
4. Delete unnecessary duplicate files using deleteFile
5. Rename documents with consistent naming conventions using renameFile
6. Create an archive index document for reference
```

## 14. Duplicate and Distribute Document Sets

```
Task: "Create personalized versions of documents for different teams."

Steps:
1. Create team-specific folders using createFolder
2. Copy master documents to each team folder using copyFile
3. Rename copied documents with team-specific names using renameFile
4. Customize document content for each team using text replacement
5. Apply team-specific formatting and branding
6. Create distribution tracking documents
```

## 15. Comprehensive File Management and Reporting

```
Task: "Generate a complete inventory and management report of all documents."

Steps:
1. Use listFolderContents to catalog all folders and their contents
2. Use getDocumentInfo to gather detailed metadata for each document
3. Create a master inventory document with all file information
4. Format the inventory as a searchable table with columns for:
   - Document name and ID
   - Creation and modification dates
   - Owner and last modifier
   - Folder location
   - File size and sharing status
5. Add summary statistics and organization recommendations
6. Set up automated folder structures for better organization
```

```

--------------------------------------------------------------------------------
/docs/index.html:
--------------------------------------------------------------------------------

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>FastMCP Google Docs Server Docs</title>
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <style>
        body { font-family: sans-serif; line-height: 1.6; padding: 20px; }
        pre { background-color: #f4f4f4; padding: 10px; border-radius: 5px; overflow-x: auto; }
        code { font-family: monospace; }
        h1, h2, h3 { border-bottom: 1px solid #eee; padding-bottom: 5px; margin-top: 20px; }
    </style>
</head>
<body>
    <div id="content"></div>

    <script type="text/markdown" id="markdown-content">
# FastMCP Google Docs Server

Connect Claude Desktop (or other MCP clients) to your Google Docs!

This server uses the Model Context Protocol (MCP) and the `fastmcp` library to provide tools for reading and appending text to Google Documents. It acts as a bridge, allowing AI assistants like Claude to interact with your documents programmatically.

**Features:**

- **Read Documents:** Provides a `readGoogleDoc` tool to fetch the text content of a specified Google Doc.
- **Append to Documents:** Provides an `appendToGoogleDoc` tool to add text to the end of a specified Google Doc.
- **Google Authentication:** Handles the OAuth 2.0 flow to securely authorize access to your Google Account.
- **MCP Compliant:** Designed for use with MCP clients like Claude Desktop.

---

## Prerequisites

Before you start, make sure you have:

1.  **Node.js and npm:** A recent version of Node.js (which includes npm) installed on your computer. You can download it from [nodejs.org](https://nodejs.org/). (Version 18 or higher recommended).
2.  **Git:** Required for cloning this repository. ([Download Git](https://git-scm.com/downloads)).
3.  **A Google Account:** The account that owns or has access to the Google Docs you want to interact with.
4.  **Command Line Familiarity:** Basic comfort using a terminal or command prompt (like Terminal on macOS/Linux, or Command Prompt/PowerShell on Windows).
5.  **Claude Desktop (Optional):** If your goal is to connect this server to Claude, you'll need the Claude Desktop application installed.

---

## Setup Instructions

Follow these steps carefully to get your own instance of the server running.

### Step 1: Google Cloud Project & Credentials (The Important Bit!)

This server needs permission to talk to Google APIs on your behalf. You'll create special "keys" (credentials) that only your server will use.

1.  **Go to Google Cloud Console:** Open your web browser and go to the [Google Cloud Console](https://console.cloud.google.com/). You might need to log in with your Google Account.
2.  **Create or Select a Project:**
    - If you don't have a project, click the project dropdown near the top and select "NEW PROJECT". Give it a name (e.g., "My MCP Docs Server") and click "CREATE".
    - If you have existing projects, you can select one or create a new one.
3.  **Enable APIs:** You need to turn on the specific Google services this server uses.
    - In the search bar at the top, type "APIs & Services" and select "Library".
    - Search for "**Google Docs API**" and click on it. Then click the "**ENABLE**" button.
    - Search for "**Google Drive API**" and click on it. Then click the "**ENABLE**" button (this is often needed for finding files or permissions).
4.  **Configure OAuth Consent Screen:** This screen tells users (usually just you) what your app wants permission for.
    - On the left menu, click "APIs & Services" -> "**OAuth consent screen**".
    - Choose User Type: Select "**External**" and click "CREATE".
    - Fill in App Information:
      - **App name:** Give it a name users will see (e.g., "Claude Docs MCP Access").
      - **User support email:** Select your email address.
      - **Developer contact information:** Enter your email address.
    - Click "**SAVE AND CONTINUE**".
    - **Scopes:** Click "**ADD OR REMOVE SCOPES**". Search for and add the following scopes:
      - `https://www.googleapis.com/auth/documents` (Allows reading/writing docs)
      - `https://www.googleapis.com/auth/drive.file` (Allows access to specific files opened/created by the app)
      - Click "**UPDATE**".
    - Click "**SAVE AND CONTINUE**".
    - **Test Users:** Click "**ADD USERS**". Enter the same Google email address you are logged in with. Click "**ADD**". This allows _you_ to use the app while it's in "testing" mode.
    - Click "**SAVE AND CONTINUE**". Review the summary and click "**BACK TO DASHBOARD**".
5.  **Create Credentials (The Keys!):**
    - On the left menu, click "APIs & Services" -> "**Credentials**".
    - Click "**+ CREATE CREDENTIALS**" at the top and choose "**OAuth client ID**".
    - **Application type:** Select "**Desktop app**" from the dropdown.
    - **Name:** Give it a name (e.g., "MCP Docs Desktop Client").
    - Click "**CREATE**".
6.  **⬇️ DOWNLOAD THE CREDENTIALS FILE:** A box will pop up showing your Client ID. Click the "**DOWNLOAD JSON**" button.
    - Save this file. It will likely be named something like `client_secret_....json`.
    - **IMPORTANT:** Rename the downloaded file to exactly `credentials.json`.
7.  ⚠️ **SECURITY WARNING:** Treat this `credentials.json` file like a password! Do not share it publicly, and **never commit it to GitHub.** Anyone with this file could potentially pretend to be _your application_ (though they'd still need user consent to access data).

### Step 2: Get the Server Code

1.  **Clone the Repository:** Open your terminal/command prompt and run:
    ```bash
    git clone https://github.com/a-bonus/google-docs-mcp.git mcp-googledocs-server
    ```
2.  **Navigate into Directory:**
    ```bash
    cd mcp-googledocs-server
    ```
3.  **Place Credentials:** Move or copy the `credentials.json` file you downloaded and renamed (from Step 1.6) directly into this `mcp-googledocs-server` folder.

### Step 3: Install Dependencies

Your server needs some helper libraries specified in the `package.json` file.

1.  In your terminal (make sure you are inside the `mcp-googledocs-server` directory), run:
    ```bash
    npm install
    ```
    This will download and install all the necessary packages into a `node_modules` folder.

### Step 4: Build the Server Code

The server is written in TypeScript (`.ts`), but we need to compile it into JavaScript (`.js`) that Node.js can run directly.

1.  In your terminal, run:
    ```bash
    npm run build
    ```
    This uses the TypeScript compiler (`tsc`) to create a `dist` folder containing the compiled JavaScript files.

### Step 5: First Run & Google Authorization (One Time Only)

Now you need to run the server once manually to grant it permission to access your Google account data. This will create a `token.json` file that saves your permission grant.

1.  In your terminal, run the _compiled_ server using `node`:
    ```bash
    node ./dist/server.js
    ```
2.  **Watch the Terminal:** The script will print:
    - Status messages (like "Attempting to authorize...").
    - An "Authorize this app by visiting this url:" message followed by a long `https://accounts.google.com/...` URL.
3.  **Authorize in Browser:**
    - Copy the entire long URL from the terminal.
    - Paste the URL into your web browser and press Enter.
    - Log in with the **same Google account** you added as a Test User in Step 1.4.
    - Google will show a screen asking for permission for your app ("Claude Docs MCP Access" or similar) to access Google Docs/Drive. Review and click "**Allow**" or "**Grant**".
4.  **Get the Authorization Code:**
    - After clicking Allow, your browser will likely try to redirect to `http://localhost` and show a **"This site can't be reached" error**. **THIS IS NORMAL!**
    - Look **carefully** at the URL in your browser's address bar. It will look like `http://localhost/?code=4/0Axxxxxxxxxxxxxx&scope=...`
    - Copy the long string of characters **between `code=` and the `&scope` part**. This is your single-use authorization code.
5.  **Paste Code into Terminal:** Go back to your terminal where the script is waiting ("Enter the code from that page here:"). Paste the code you just copied.
6.  **Press Enter.**
7.  **Success!** The script should print:
    - "Authentication successful!"
    - "Token stored to .../token.json"
    - It will then finish starting and likely print "Awaiting MCP client connection via stdio..." or similar, and then exit (or you can press `Ctrl+C` to stop it).
8.  ✅ **Check:** You should now see a new file named `token.json` in your `mcp-googledocs-server` folder.
9.  ⚠️ **SECURITY WARNING:** This `token.json` file contains the key that allows the server to access your Google account _without_ asking again. Protect it like a password. **Do not commit it to GitHub.** The included `.gitignore` file should prevent this automatically.

### Step 6: Configure Claude Desktop (Optional)

If you want to use this server with Claude Desktop, you need to tell Claude how to run it.

1.  **Find Your Absolute Path:** You need the full path to the server code.
    - In your terminal, make sure you are still inside the `mcp-googledocs-server` directory.
    - Run the `pwd` command (on macOS/Linux) or `cd` (on Windows, just displays the path).
    - Copy the full path (e.g., `/Users/yourname/projects/mcp-googledocs-server` or `C:\Users\yourname\projects\mcp-googledocs-server`).
2.  **Locate `mcp_config.json`:** Find Claude's configuration file:
    - **macOS:** `~/Library/Application Support/Claude/mcp_config.json` (You might need to use Finder's "Go" -> "Go to Folder..." menu and paste `~/Library/Application Support/Claude/`)
    - **Windows:** `%APPDATA%\Claude\mcp_config.json` (Paste `%APPDATA%\Claude` into File Explorer's address bar)
    - **Linux:** `~/.config/Claude/mcp_config.json`
    - _If the `Claude` folder or `mcp_config.json` file doesn't exist, create them._
3.  **Edit `mcp_config.json`:** Open the file in a text editor. Add or modify the `mcpServers` section like this, **replacing `/PATH/TO/YOUR/CLONED/REPO` with the actual absolute path you copied in Step 6.1**:

    ```json
    {
      "mcpServers": {
        "google-docs-mcp": {
          "command": "node",
          "args": [
            "/PATH/TO/YOUR/CLONED/REPO/mcp-googledocs-server/dist/server.js"
          ],
          "env": {}
        }
        // Add commas here if you have other servers defined
      }
      // Other Claude settings might be here
    }
    ```

    - **Make sure the path in `"args"` is correct and absolute!**
    - If the file already existed, carefully merge this entry into the existing `mcpServers` object. Ensure the JSON is valid (check commas!).

4.  **Save `mcp_config.json`.**
5.  **Restart Claude Desktop:** Close Claude completely and reopen it.

---

## Usage with Claude Desktop

Once configured, you should be able to use the tools in your chats with Claude:

- "Use the `google-docs-mcp` server to read the document with ID `YOUR_GOOGLE_DOC_ID`."
- "Can you get the content of Google Doc `YOUR_GOOGLE_DOC_ID`?"
- "Append 'This was added by Claude!' to document `YOUR_GOOGLE_DOC_ID` using the `google-docs-mcp` tool."

Remember to replace `YOUR_GOOGLE_DOC_ID` with the actual ID from a Google Doc's URL (the long string between `/d/` and `/edit`).

Claude will automatically launch your server in the background when needed using the command you provided. You do **not** need to run `node ./dist/server.js` manually anymore.

---

## Security & Token Storage

- **`.gitignore`:** This repository includes a `.gitignore` file which should prevent you from accidentally committing your sensitive `credentials.json` and `token.json` files. **Do not remove these lines from `.gitignore`**.
- **Token Storage:** This server stores the Google authorization token (`token.json`) directly in the project folder for simplicity during setup. In production or more security-sensitive environments, consider storing this token more securely, such as using system keychains, encrypted files, or dedicated secret management services.

---

## Troubleshooting

- **Claude shows "Failed" or "Could not attach":**
  - Double-check the absolute path in `mcp_config.json`.
  - Ensure you ran `npm run build` successfully and the `dist` folder exists.
  - Try running the command from `mcp_config.json` manually in your terminal: `node /PATH/TO/YOUR/CLONED/REPO/mcp-googledocs-server/dist/server.js`. Look for any errors printed.
  - Check the Claude Desktop logs (see the official MCP debugging guide).
  - Make sure all `console.log` status messages in the server code were changed to `console.error`.
- **Google Authorization Errors:**
  - Ensure you enabled the correct APIs (Docs, Drive).
  - Make sure you added your email as a Test User on the OAuth Consent Screen.
  - Verify the `credentials.json` file is correctly placed in the project root.

---

## License

This project is licensed under the MIT License - see the `LICENSE` file for details. (Note: You should add a `LICENSE` file containing the MIT License text to your repository).

---

```

--------------------------------------------------------------------------------
/src/googleDocsApiHelpers.ts:
--------------------------------------------------------------------------------

```typescript
// src/googleDocsApiHelpers.ts
import { google, docs_v1 } from 'googleapis';
import { OAuth2Client } from 'google-auth-library';
import { UserError } from 'fastmcp';
import { TextStyleArgs, ParagraphStyleArgs, hexToRgbColor, NotImplementedError } from './types.js';

type Docs = docs_v1.Docs; // Alias for convenience

// --- Constants ---
const MAX_BATCH_UPDATE_REQUESTS = 50; // Google API limits batch size

// --- Core Helper to Execute Batch Updates ---
export async function executeBatchUpdate(docs: Docs, documentId: string, requests: docs_v1.Schema$Request[]): Promise<docs_v1.Schema$BatchUpdateDocumentResponse> {
if (!requests || requests.length === 0) {
// console.warn("executeBatchUpdate called with no requests.");
return {}; // Nothing to do
}

    // TODO: Consider splitting large request arrays into multiple batches if needed
    if (requests.length > MAX_BATCH_UPDATE_REQUESTS) {
         console.warn(`Attempting batch update with ${requests.length} requests, exceeding typical limits. May fail.`);
    }

    try {
        const response = await docs.documents.batchUpdate({
            documentId: documentId,
            requestBody: { requests },
        });
        return response.data;
    } catch (error: any) {
        console.error(`Google API batchUpdate Error for doc ${documentId}:`, error.response?.data || error.message);
        // Translate common API errors to UserErrors
        if (error.code === 400 && error.message.includes('Invalid requests')) {
             // Try to extract more specific info if available
             const details = error.response?.data?.error?.details;
             let detailMsg = '';
             if (details && Array.isArray(details)) {
                 detailMsg = details.map(d => d.description || JSON.stringify(d)).join('; ');
             }
            throw new UserError(`Invalid request sent to Google Docs API. Details: ${detailMsg || error.message}`);
        }
        if (error.code === 404) throw new UserError(`Document not found (ID: ${documentId}). Check the ID.`);
        if (error.code === 403) throw new UserError(`Permission denied for document (ID: ${documentId}). Ensure the authenticated user has edit access.`);
        // Generic internal error for others
        throw new Error(`Google API Error (${error.code}): ${error.message}`);
    }

}

// --- Text Finding Helper ---
// This improved version is more robust in handling various text structure scenarios
export async function findTextRange(docs: Docs, documentId: string, textToFind: string, instance: number = 1): Promise<{ startIndex: number; endIndex: number } | null> {
try {
    // Request more detailed information about the document structure
    const res = await docs.documents.get({
        documentId,
        // Request more fields to handle various container types (not just paragraphs)
        fields: 'body(content(paragraph(elements(startIndex,endIndex,textRun(content))),table,sectionBreak,tableOfContents,startIndex,endIndex))',
    });

    if (!res.data.body?.content) {
        console.warn(`No content found in document ${documentId}`);
        return null;
    }

    // More robust text collection and index tracking
    let fullText = '';
    const segments: { text: string, start: number, end: number }[] = [];
    
    // Process all content elements, including structural ones
    const collectTextFromContent = (content: any[]) => {
        content.forEach(element => {
            // Handle paragraph elements
            if (element.paragraph?.elements) {
                element.paragraph.elements.forEach((pe: any) => {
                    if (pe.textRun?.content && pe.startIndex !== undefined && pe.endIndex !== undefined) {
                        const content = pe.textRun.content;
                        fullText += content;
                        segments.push({ 
                            text: content, 
                            start: pe.startIndex, 
                            end: pe.endIndex 
                        });
                    }
                });
            }
            
            // Handle table elements - this is simplified and might need expansion
            if (element.table && element.table.tableRows) {
                element.table.tableRows.forEach((row: any) => {
                    if (row.tableCells) {
                        row.tableCells.forEach((cell: any) => {
                            if (cell.content) {
                                collectTextFromContent(cell.content);
                            }
                        });
                    }
                });
            }
            
            // Add handling for other structural elements as needed
        });
    };
    
    collectTextFromContent(res.data.body.content);
    
    // Sort segments by starting position to ensure correct ordering
    segments.sort((a, b) => a.start - b.start);
    
    console.log(`Document ${documentId} contains ${segments.length} text segments and ${fullText.length} characters in total.`);
    
    // Find the specified instance of the text
    let startIndex = -1;
    let endIndex = -1;
    let foundCount = 0;
    let searchStartIndex = 0;

    while (foundCount < instance) {
        const currentIndex = fullText.indexOf(textToFind, searchStartIndex);
        if (currentIndex === -1) {
            console.log(`Search text "${textToFind}" not found for instance ${foundCount + 1} (requested: ${instance})`);
            break;
        }

        foundCount++;
        console.log(`Found instance ${foundCount} of "${textToFind}" at position ${currentIndex} in full text`);
        
        if (foundCount === instance) {
            const targetStartInFullText = currentIndex;
            const targetEndInFullText = currentIndex + textToFind.length;
            let currentPosInFullText = 0;
            
            console.log(`Target text range in full text: ${targetStartInFullText}-${targetEndInFullText}`);

            for (const seg of segments) {
                const segStartInFullText = currentPosInFullText;
                const segTextLength = seg.text.length;
                const segEndInFullText = segStartInFullText + segTextLength;

                // Map from reconstructed text position to actual document indices
                if (startIndex === -1 && targetStartInFullText >= segStartInFullText && targetStartInFullText < segEndInFullText) {
                    startIndex = seg.start + (targetStartInFullText - segStartInFullText);
                    console.log(`Mapped start to segment ${seg.start}-${seg.end}, position ${startIndex}`);
                }
                
                if (targetEndInFullText > segStartInFullText && targetEndInFullText <= segEndInFullText) {
                    endIndex = seg.start + (targetEndInFullText - segStartInFullText);
                    console.log(`Mapped end to segment ${seg.start}-${seg.end}, position ${endIndex}`);
                    break;
                }
                
                currentPosInFullText = segEndInFullText;
            }

            if (startIndex === -1 || endIndex === -1) {
                console.warn(`Failed to map text "${textToFind}" instance ${instance} to actual document indices`);
                // Reset and try next occurrence
                startIndex = -1; 
                endIndex = -1;
                searchStartIndex = currentIndex + 1;
                foundCount--;
                continue;
            }
            
            console.log(`Successfully mapped "${textToFind}" to document range ${startIndex}-${endIndex}`);
            return { startIndex, endIndex };
        }
        
        // Prepare for next search iteration
        searchStartIndex = currentIndex + 1;
    }

    console.warn(`Could not find instance ${instance} of text "${textToFind}" in document ${documentId}`);
    return null; // Instance not found or mapping failed for all attempts
} catch (error: any) {
    console.error(`Error finding text "${textToFind}" in doc ${documentId}: ${error.message || 'Unknown error'}`);
    if (error.code === 404) throw new UserError(`Document not found while searching text (ID: ${documentId}).`);
    if (error.code === 403) throw new UserError(`Permission denied while searching text in doc ${documentId}.`);
    throw new Error(`Failed to retrieve doc for text searching: ${error.message || 'Unknown error'}`);
}
}

// --- Paragraph Boundary Helper ---
// Enhanced version to handle document structural elements more robustly
export async function getParagraphRange(docs: Docs, documentId: string, indexWithin: number): Promise<{ startIndex: number; endIndex: number } | null> {
try {
    console.log(`Finding paragraph containing index ${indexWithin} in document ${documentId}`);
    
    // Request more detailed document structure to handle nested elements
    const res = await docs.documents.get({
        documentId,
        // Request more comprehensive structure information
        fields: 'body(content(startIndex,endIndex,paragraph,table,sectionBreak,tableOfContents))',
    });

    if (!res.data.body?.content) {
        console.warn(`No content found in document ${documentId}`);
        return null;
    }

    // Find paragraph containing the index
    // We'll look at all structural elements recursively
    const findParagraphInContent = (content: any[]): { startIndex: number; endIndex: number } | null => {
        for (const element of content) {
            // Check if we have element boundaries defined
            if (element.startIndex !== undefined && element.endIndex !== undefined) {
                // Check if index is within this element's range first
                if (indexWithin >= element.startIndex && indexWithin < element.endIndex) {
                    // If it's a paragraph, we've found our target
                    if (element.paragraph) {
                        console.log(`Found paragraph containing index ${indexWithin}, range: ${element.startIndex}-${element.endIndex}`);
                        return { 
                            startIndex: element.startIndex, 
                            endIndex: element.endIndex 
                        };
                    }
                    
                    // If it's a table, we need to check cells recursively
                    if (element.table && element.table.tableRows) {
                        console.log(`Index ${indexWithin} is within a table, searching cells...`);
                        for (const row of element.table.tableRows) {
                            if (row.tableCells) {
                                for (const cell of row.tableCells) {
                                    if (cell.content) {
                                        const result = findParagraphInContent(cell.content);
                                        if (result) return result;
                                    }
                                }
                            }
                        }
                    }
                    
                    // For other structural elements, we didn't find a paragraph
                    // but we know the index is within this element
                    console.warn(`Index ${indexWithin} is within element (${element.startIndex}-${element.endIndex}) but not in a paragraph`);
                }
            }
        }
        
        return null;
    };

    const paragraphRange = findParagraphInContent(res.data.body.content);
    
    if (!paragraphRange) {
        console.warn(`Could not find paragraph containing index ${indexWithin}`);
    } else {
        console.log(`Returning paragraph range: ${paragraphRange.startIndex}-${paragraphRange.endIndex}`);
    }
    
    return paragraphRange;

} catch (error: any) {
    console.error(`Error getting paragraph range for index ${indexWithin} in doc ${documentId}: ${error.message || 'Unknown error'}`);
    if (error.code === 404) throw new UserError(`Document not found while finding paragraph (ID: ${documentId}).`);
    if (error.code === 403) throw new UserError(`Permission denied while accessing doc ${documentId}.`);
    throw new Error(`Failed to find paragraph: ${error.message || 'Unknown error'}`);
}
}

// --- Style Request Builders ---

export function buildUpdateTextStyleRequest(
startIndex: number,
endIndex: number,
style: TextStyleArgs
): { request: docs_v1.Schema$Request, fields: string[] } | null {
    const textStyle: docs_v1.Schema$TextStyle = {};
const fieldsToUpdate: string[] = [];

    if (style.bold !== undefined) { textStyle.bold = style.bold; fieldsToUpdate.push('bold'); }
    if (style.italic !== undefined) { textStyle.italic = style.italic; fieldsToUpdate.push('italic'); }
    if (style.underline !== undefined) { textStyle.underline = style.underline; fieldsToUpdate.push('underline'); }
    if (style.strikethrough !== undefined) { textStyle.strikethrough = style.strikethrough; fieldsToUpdate.push('strikethrough'); }
    if (style.fontSize !== undefined) { textStyle.fontSize = { magnitude: style.fontSize, unit: 'PT' }; fieldsToUpdate.push('fontSize'); }
    if (style.fontFamily !== undefined) { textStyle.weightedFontFamily = { fontFamily: style.fontFamily }; fieldsToUpdate.push('weightedFontFamily'); }
    if (style.foregroundColor !== undefined) {
        const rgbColor = hexToRgbColor(style.foregroundColor);
        if (!rgbColor) throw new UserError(`Invalid foreground hex color format: ${style.foregroundColor}`);
        textStyle.foregroundColor = { color: { rgbColor: rgbColor } }; fieldsToUpdate.push('foregroundColor');
    }
     if (style.backgroundColor !== undefined) {
        const rgbColor = hexToRgbColor(style.backgroundColor);
        if (!rgbColor) throw new UserError(`Invalid background hex color format: ${style.backgroundColor}`);
        textStyle.backgroundColor = { color: { rgbColor: rgbColor } }; fieldsToUpdate.push('backgroundColor');
    }
    if (style.linkUrl !== undefined) {
        textStyle.link = { url: style.linkUrl }; fieldsToUpdate.push('link');
    }
    // TODO: Handle clearing formatting

    if (fieldsToUpdate.length === 0) return null; // No styles to apply

    const request: docs_v1.Schema$Request = {
        updateTextStyle: {
            range: { startIndex, endIndex },
            textStyle: textStyle,
            fields: fieldsToUpdate.join(','),
        }
    };
    return { request, fields: fieldsToUpdate };

}

export function buildUpdateParagraphStyleRequest(
startIndex: number,
endIndex: number,
style: ParagraphStyleArgs
): { request: docs_v1.Schema$Request, fields: string[] } | null {
    // Create style object and track which fields to update
    const paragraphStyle: docs_v1.Schema$ParagraphStyle = {};
    const fieldsToUpdate: string[] = [];

    console.log(`Building paragraph style request for range ${startIndex}-${endIndex} with options:`, style);

    // Process alignment option (LEFT, CENTER, RIGHT, JUSTIFIED)
    if (style.alignment !== undefined) { 
        paragraphStyle.alignment = style.alignment; 
        fieldsToUpdate.push('alignment'); 
        console.log(`Setting alignment to ${style.alignment}`);
    }
    
    // Process indentation options
    if (style.indentStart !== undefined) { 
        paragraphStyle.indentStart = { magnitude: style.indentStart, unit: 'PT' }; 
        fieldsToUpdate.push('indentStart'); 
        console.log(`Setting left indent to ${style.indentStart}pt`);
    }
    
    if (style.indentEnd !== undefined) { 
        paragraphStyle.indentEnd = { magnitude: style.indentEnd, unit: 'PT' }; 
        fieldsToUpdate.push('indentEnd'); 
        console.log(`Setting right indent to ${style.indentEnd}pt`);
    }
    
    // Process spacing options
    if (style.spaceAbove !== undefined) { 
        paragraphStyle.spaceAbove = { magnitude: style.spaceAbove, unit: 'PT' }; 
        fieldsToUpdate.push('spaceAbove'); 
        console.log(`Setting space above to ${style.spaceAbove}pt`);
    }
    
    if (style.spaceBelow !== undefined) { 
        paragraphStyle.spaceBelow = { magnitude: style.spaceBelow, unit: 'PT' }; 
        fieldsToUpdate.push('spaceBelow'); 
        console.log(`Setting space below to ${style.spaceBelow}pt`);
    }
    
    // Process named style types (headings, etc.)
    if (style.namedStyleType !== undefined) { 
        paragraphStyle.namedStyleType = style.namedStyleType; 
        fieldsToUpdate.push('namedStyleType'); 
        console.log(`Setting named style to ${style.namedStyleType}`);
    }
    
    // Process page break control
    if (style.keepWithNext !== undefined) { 
        paragraphStyle.keepWithNext = style.keepWithNext; 
        fieldsToUpdate.push('keepWithNext'); 
        console.log(`Setting keepWithNext to ${style.keepWithNext}`);
    }

    // Verify we have styles to apply
    if (fieldsToUpdate.length === 0) {
        console.warn("No paragraph styling options were provided");
        return null; // No styles to apply
    }

    // Build the request object
    const request: docs_v1.Schema$Request = {
        updateParagraphStyle: {
            range: { startIndex, endIndex },
            paragraphStyle: paragraphStyle,
            fields: fieldsToUpdate.join(','),
        }
    };
    
    console.log(`Created paragraph style request with fields: ${fieldsToUpdate.join(', ')}`);
    return { request, fields: fieldsToUpdate };
}

// --- Specific Feature Helpers ---

export async function createTable(docs: Docs, documentId: string, rows: number, columns: number, index: number): Promise<docs_v1.Schema$BatchUpdateDocumentResponse> {
    if (rows < 1 || columns < 1) {
        throw new UserError("Table must have at least 1 row and 1 column.");
    }
    const request: docs_v1.Schema$Request = {
insertTable: {
location: { index },
rows: rows,
columns: columns,
}
};
return executeBatchUpdate(docs, documentId, [request]);
}

export async function insertText(docs: Docs, documentId: string, text: string, index: number): Promise<docs_v1.Schema$BatchUpdateDocumentResponse> {
    if (!text) return {}; // Nothing to insert
    const request: docs_v1.Schema$Request = {
insertText: {
location: { index },
text: text,
}
};
return executeBatchUpdate(docs, documentId, [request]);
}

// --- Complex / Stubbed Helpers ---

export async function findParagraphsMatchingStyle(
docs: Docs,
documentId: string,
styleCriteria: any // Define a proper type for criteria (e.g., { fontFamily: 'Arial', bold: true })
): Promise<{ startIndex: number; endIndex: number }[]> {
// TODO: Implement logic
// 1. Get document content with paragraph elements and their styles.
// 2. Iterate through paragraphs.
// 3. For each paragraph, check if its computed style matches the criteria.
// 4. Return ranges of matching paragraphs.
console.warn("findParagraphsMatchingStyle is not implemented.");
throw new NotImplementedError("Finding paragraphs by style criteria is not yet implemented.");
// return [];
}

export async function detectAndFormatLists(
docs: Docs,
documentId: string,
startIndex?: number,
endIndex?: number
): Promise<docs_v1.Schema$BatchUpdateDocumentResponse> {
// TODO: Implement complex logic
// 1. Get document content (paragraphs, text runs) in the specified range (or whole doc).
// 2. Iterate through paragraphs.
// 3. Identify sequences of paragraphs starting with list-like markers (e.g., "-", "*", "1.", "a)").
// 4. Determine nesting levels based on indentation or marker patterns.
// 5. Generate CreateParagraphBulletsRequests for the identified sequences.
// 6. Potentially delete the original marker text.
// 7. Execute the batch update.
console.warn("detectAndFormatLists is not implemented.");
throw new NotImplementedError("Automatic list detection and formatting is not yet implemented.");
// return {};
}

export async function addCommentHelper(docs: Docs, documentId: string, text: string, startIndex: number, endIndex: number): Promise<void> {
// NOTE: Adding comments typically requires the Google Drive API v3 and different scopes!
// 'https://www.googleapis.com/auth/drive' or more specific comment scopes.
// This helper is a placeholder assuming Drive API client (`drive`) is available and authorized.
/*
const drive = google.drive({version: 'v3', auth: authClient}); // Assuming authClient is available
await drive.comments.create({
fileId: documentId,
requestBody: {
content: text,
anchor: JSON.stringify({ // Anchor format might need verification
'type': 'workbook#textAnchor', // Or appropriate type for Docs
'refs': [{
'docRevisionId': 'head', // Or specific revision
'range': {
'start': startIndex,
'end': endIndex,
}
}]
})
},
fields: 'id'
});
*/
console.warn("addCommentHelper requires Google Drive API and is not implemented.");
throw new NotImplementedError("Adding comments requires Drive API setup and is not yet implemented.");
}

// --- Image Insertion Helpers ---

/**
 * Inserts an inline image into a document from a publicly accessible URL
 * @param docs - Google Docs API client
 * @param documentId - The document ID
 * @param imageUrl - Publicly accessible URL to the image
 * @param index - Position in the document where image should be inserted (1-based)
 * @param width - Optional width in points
 * @param height - Optional height in points
 * @returns Promise with batch update response
 */
export async function insertInlineImage(
    docs: Docs,
    documentId: string,
    imageUrl: string,
    index: number,
    width?: number,
    height?: number
): Promise<docs_v1.Schema$BatchUpdateDocumentResponse> {
    // Validate URL format
    try {
        new URL(imageUrl);
    } catch (e) {
        throw new UserError(`Invalid image URL format: ${imageUrl}`);
    }

    // Build the insertInlineImage request
    const request: docs_v1.Schema$Request = {
        insertInlineImage: {
            location: { index },
            uri: imageUrl,
            ...(width && height && {
                objectSize: {
                    height: { magnitude: height, unit: 'PT' },
                    width: { magnitude: width, unit: 'PT' }
                }
            })
        }
    };

    return executeBatchUpdate(docs, documentId, [request]);
}

/**
 * Uploads a local image file to Google Drive and returns its public URL
 * @param drive - Google Drive API client
 * @param localFilePath - Path to the local image file
 * @param parentFolderId - Optional parent folder ID (defaults to root)
 * @returns Promise with the public webContentLink URL
 */
export async function uploadImageToDrive(
    drive: any, // drive_v3.Drive type
    localFilePath: string,
    parentFolderId?: string
): Promise<string> {
    const fs = await import('fs');
    const path = await import('path');

    // Verify file exists
    if (!fs.existsSync(localFilePath)) {
        throw new UserError(`Image file not found: ${localFilePath}`);
    }

    // Get file name and mime type
    const fileName = path.basename(localFilePath);
    const mimeTypeMap: { [key: string]: string } = {
        '.jpg': 'image/jpeg',
        '.jpeg': 'image/jpeg',
        '.png': 'image/png',
        '.gif': 'image/gif',
        '.bmp': 'image/bmp',
        '.webp': 'image/webp',
        '.svg': 'image/svg+xml'
    };

    const ext = path.extname(localFilePath).toLowerCase();
    const mimeType = mimeTypeMap[ext] || 'application/octet-stream';

    // Upload file to Drive
    const fileMetadata: any = {
        name: fileName,
        mimeType: mimeType
    };

    if (parentFolderId) {
        fileMetadata.parents = [parentFolderId];
    }

    const media = {
        mimeType: mimeType,
        body: fs.createReadStream(localFilePath)
    };

    const uploadResponse = await drive.files.create({
        requestBody: fileMetadata,
        media: media,
        fields: 'id,webViewLink,webContentLink'
    });

    const fileId = uploadResponse.data.id;
    if (!fileId) {
        throw new Error('Failed to upload image to Drive - no file ID returned');
    }

    // Make the file publicly readable
    await drive.permissions.create({
        fileId: fileId,
        requestBody: {
            role: 'reader',
            type: 'anyone'
        }
    });

    // Get the webContentLink
    const fileInfo = await drive.files.get({
        fileId: fileId,
        fields: 'webContentLink'
    });

    const webContentLink = fileInfo.data.webContentLink;
    if (!webContentLink) {
        throw new Error('Failed to get public URL for uploaded image');
    }

    return webContentLink;
}
```

--------------------------------------------------------------------------------
/src/server.ts:
--------------------------------------------------------------------------------

```typescript
// src/server.ts
import { FastMCP, UserError } from 'fastmcp';
import { z } from 'zod';
import { google, docs_v1, drive_v3 } from 'googleapis';
import { authorize } from './auth.js';
import { OAuth2Client } from 'google-auth-library';

// Import types and helpers
import {
DocumentIdParameter,
RangeParameters,
OptionalRangeParameters,
TextFindParameter,
TextStyleParameters,
TextStyleArgs,
ParagraphStyleParameters,
ParagraphStyleArgs,
ApplyTextStyleToolParameters, ApplyTextStyleToolArgs,
ApplyParagraphStyleToolParameters, ApplyParagraphStyleToolArgs,
NotImplementedError
} from './types.js';
import * as GDocsHelpers from './googleDocsApiHelpers.js';

let authClient: OAuth2Client | null = null;
let googleDocs: docs_v1.Docs | null = null;
let googleDrive: drive_v3.Drive | null = null;

// --- Initialization ---
async function initializeGoogleClient() {
if (googleDocs && googleDrive) return { authClient, googleDocs, googleDrive };
if (!authClient) { // Check authClient instead of googleDocs to allow re-attempt
try {
console.error("Attempting to authorize Google API client...");
const client = await authorize();
authClient = client; // Assign client here
googleDocs = google.docs({ version: 'v1', auth: authClient });
googleDrive = google.drive({ version: 'v3', auth: authClient });
console.error("Google API client authorized successfully.");
} catch (error) {
console.error("FATAL: Failed to initialize Google API client:", error);
authClient = null; // Reset on failure
googleDocs = null;
googleDrive = null;
// Decide if server should exit or just fail tools
throw new Error("Google client initialization failed. Cannot start server tools.");
}
}
// Ensure googleDocs and googleDrive are set if authClient is valid
if (authClient && !googleDocs) {
googleDocs = google.docs({ version: 'v1', auth: authClient });
}
if (authClient && !googleDrive) {
googleDrive = google.drive({ version: 'v3', auth: authClient });
}

if (!googleDocs || !googleDrive) {
throw new Error("Google Docs and Drive clients could not be initialized.");
}

return { authClient, googleDocs, googleDrive };
}

// Set up process-level unhandled error/rejection handlers to prevent crashes
process.on('uncaughtException', (error) => {
  console.error('Uncaught Exception:', error);
  // Don't exit process, just log the error and continue
  // This will catch timeout errors that might otherwise crash the server
});

process.on('unhandledRejection', (reason, promise) => {
  console.error('Unhandled Promise Rejection:', reason);
  // Don't exit process, just log the error and continue
});

const server = new FastMCP({
  name: 'Ultimate Google Docs MCP Server',
  version: '1.0.0'
});

// --- Helper to get Docs client within tools ---
async function getDocsClient() {
const { googleDocs: docs } = await initializeGoogleClient();
if (!docs) {
throw new UserError("Google Docs client is not initialized. Authentication might have failed during startup or lost connection.");
}
return docs;
}

// --- Helper to get Drive client within tools ---
async function getDriveClient() {
const { googleDrive: drive } = await initializeGoogleClient();
if (!drive) {
throw new UserError("Google Drive client is not initialized. Authentication might have failed during startup or lost connection.");
}
return drive;
}

// === HELPER FUNCTIONS ===

/**
 * Converts Google Docs JSON structure to Markdown format
 */
function convertDocsJsonToMarkdown(docData: any): string {
    let markdown = '';
    
    if (!docData.body?.content) {
        return 'Document appears to be empty.';
    }
    
    docData.body.content.forEach((element: any) => {
        if (element.paragraph) {
            markdown += convertParagraphToMarkdown(element.paragraph);
        } else if (element.table) {
            markdown += convertTableToMarkdown(element.table);
        } else if (element.sectionBreak) {
            markdown += '\n---\n\n'; // Section break as horizontal rule
        }
    });
    
    return markdown.trim();
}

/**
 * Converts a paragraph element to markdown
 */
function convertParagraphToMarkdown(paragraph: any): string {
    let text = '';
    let isHeading = false;
    let headingLevel = 0;
    let isList = false;
    let listType = '';
    
    // Check paragraph style for headings and lists
    if (paragraph.paragraphStyle?.namedStyleType) {
        const styleType = paragraph.paragraphStyle.namedStyleType;
        if (styleType.startsWith('HEADING_')) {
            isHeading = true;
            headingLevel = parseInt(styleType.replace('HEADING_', ''));
        } else if (styleType === 'TITLE') {
            isHeading = true;
            headingLevel = 1;
        } else if (styleType === 'SUBTITLE') {
            isHeading = true;
            headingLevel = 2;
        }
    }
    
    // Check for bullet lists
    if (paragraph.bullet) {
        isList = true;
        listType = paragraph.bullet.listId ? 'bullet' : 'bullet';
    }
    
    // Process text elements
    if (paragraph.elements) {
        paragraph.elements.forEach((element: any) => {
            if (element.textRun) {
                text += convertTextRunToMarkdown(element.textRun);
            }
        });
    }
    
    // Format based on style
    if (isHeading && text.trim()) {
        const hashes = '#'.repeat(Math.min(headingLevel, 6));
        return `${hashes} ${text.trim()}\n\n`;
    } else if (isList && text.trim()) {
        return `- ${text.trim()}\n`;
    } else if (text.trim()) {
        return `${text.trim()}\n\n`;
    }
    
    return '\n'; // Empty paragraph
}

/**
 * Converts a text run to markdown with formatting
 */
function convertTextRunToMarkdown(textRun: any): string {
    let text = textRun.content || '';
    
    if (textRun.textStyle) {
        const style = textRun.textStyle;
        
        // Apply formatting
        if (style.bold && style.italic) {
            text = `***${text}***`;
        } else if (style.bold) {
            text = `**${text}**`;
        } else if (style.italic) {
            text = `*${text}*`;
        }
        
        if (style.underline && !style.link) {
            // Markdown doesn't have native underline, use HTML
            text = `<u>${text}</u>`;
        }
        
        if (style.strikethrough) {
            text = `~~${text}~~`;
        }
        
        if (style.link?.url) {
            text = `[${text}](${style.link.url})`;
        }
    }
    
    return text;
}

/**
 * Converts a table to markdown format
 */
function convertTableToMarkdown(table: any): string {
    if (!table.tableRows || table.tableRows.length === 0) {
        return '';
    }
    
    let markdown = '\n';
    let isFirstRow = true;
    
    table.tableRows.forEach((row: any) => {
        if (!row.tableCells) return;
        
        let rowText = '|';
        row.tableCells.forEach((cell: any) => {
            let cellText = '';
            if (cell.content) {
                cell.content.forEach((element: any) => {
                    if (element.paragraph?.elements) {
                        element.paragraph.elements.forEach((pe: any) => {
                            if (pe.textRun?.content) {
                                cellText += pe.textRun.content.replace(/\n/g, ' ').trim();
                            }
                        });
                    }
                });
            }
            rowText += ` ${cellText} |`;
        });
        
        markdown += rowText + '\n';
        
        // Add header separator after first row
        if (isFirstRow) {
            let separator = '|';
            for (let i = 0; i < row.tableCells.length; i++) {
                separator += ' --- |';
            }
            markdown += separator + '\n';
            isFirstRow = false;
        }
    });
    
    return markdown + '\n';
}

// === TOOL DEFINITIONS ===

// --- Foundational Tools ---

server.addTool({
name: 'readGoogleDoc',
description: 'Reads the content of a specific Google Document, optionally returning structured data.',
parameters: DocumentIdParameter.extend({
format: z.enum(['text', 'json', 'markdown']).optional().default('text')
.describe("Output format: 'text' (plain text), 'json' (raw API structure, complex), 'markdown' (experimental conversion)."),
maxLength: z.number().optional().describe('Maximum character limit for text output. If not specified, returns full document content. Use this to limit very large documents.')
}),
execute: async (args, { log }) => {
const docs = await getDocsClient();
log.info(`Reading Google Doc: ${args.documentId}, Format: ${args.format}`);

    try {
        const fields = args.format === 'json' || args.format === 'markdown'
            ? '*' // Get everything for structure analysis
            : 'body(content(paragraph(elements(textRun(content)))))'; // Just text content

        const res = await docs.documents.get({
            documentId: args.documentId,
            fields: fields,
        });
        log.info(`Fetched doc: ${args.documentId}`);

        if (args.format === 'json') {
            const jsonContent = JSON.stringify(res.data, null, 2);
            // Apply length limit to JSON if specified
            if (args.maxLength && jsonContent.length > args.maxLength) {
                return jsonContent.substring(0, args.maxLength) + `\n... [JSON truncated: ${jsonContent.length} total chars]`;
            }
            return jsonContent;
        }

        if (args.format === 'markdown') {
            const markdownContent = convertDocsJsonToMarkdown(res.data);
            const totalLength = markdownContent.length;
            log.info(`Generated markdown: ${totalLength} characters`);
            
            // Apply length limit to markdown if specified
            if (args.maxLength && totalLength > args.maxLength) {
                const truncatedContent = markdownContent.substring(0, args.maxLength);
                return `${truncatedContent}\n\n... [Markdown truncated to ${args.maxLength} chars of ${totalLength} total. Use maxLength parameter to adjust limit or remove it to get full content.]`;
            }
            
            return markdownContent;
        }

        // Default: Text format - extract all text content
        let textContent = '';
        let elementCount = 0;
        
        // Process all content elements
        res.data.body?.content?.forEach(element => {
            elementCount++;
            
            // Handle paragraphs
            if (element.paragraph?.elements) {
                element.paragraph.elements.forEach(pe => {
                    if (pe.textRun?.content) {
                        textContent += pe.textRun.content;
                    }
                });
            }
            
            // Handle tables
            if (element.table?.tableRows) {
                element.table.tableRows.forEach(row => {
                    row.tableCells?.forEach(cell => {
                        cell.content?.forEach(cellElement => {
                            cellElement.paragraph?.elements?.forEach(pe => {
                                if (pe.textRun?.content) {
                                    textContent += pe.textRun.content;
                                }
                            });
                        });
                    });
                });
            }
        });

        if (!textContent.trim()) return "Document found, but appears empty.";

        const totalLength = textContent.length;
        log.info(`Document contains ${totalLength} characters across ${elementCount} elements`);
        log.info(`maxLength parameter: ${args.maxLength || 'not specified'}`);

        // Apply length limit only if specified
        if (args.maxLength && totalLength > args.maxLength) {
            const truncatedContent = textContent.substring(0, args.maxLength);
            log.info(`Truncating content from ${totalLength} to ${args.maxLength} characters`);
            return `Content (truncated to ${args.maxLength} chars of ${totalLength} total):\n---\n${truncatedContent}\n\n... [Document continues for ${totalLength - args.maxLength} more characters. Use maxLength parameter to adjust limit or remove it to get full content.]`;
        }

        // Return full content
        const fullResponse = `Content (${totalLength} characters):\n---\n${textContent}`;
        const responseLength = fullResponse.length;
        log.info(`Returning full content: ${responseLength} characters in response (${totalLength} content + ${responseLength - totalLength} metadata)`);
        
        return fullResponse;

    } catch (error: any) {
         log.error(`Error reading doc ${args.documentId}: ${error.message || error}`);
         // Handle errors thrown by helpers or API directly
         if (error instanceof UserError) throw error;
         if (error instanceof NotImplementedError) throw error;
         // Generic fallback for API errors not caught by helpers
          if (error.code === 404) throw new UserError(`Doc not found (ID: ${args.documentId}).`);
          if (error.code === 403) throw new UserError(`Permission denied for doc (ID: ${args.documentId}).`);
         throw new UserError(`Failed to read doc: ${error.message || 'Unknown error'}`);
    }

},
});

server.addTool({
name: 'appendToGoogleDoc',
description: 'Appends text to the very end of a specific Google Document.',
parameters: DocumentIdParameter.extend({
textToAppend: z.string().min(1).describe('The text to add to the end.'),
addNewlineIfNeeded: z.boolean().optional().default(true).describe("Automatically add a newline before the appended text if the doc doesn't end with one."),
}),
execute: async (args, { log }) => {
const docs = await getDocsClient();
log.info(`Appending to Google Doc: ${args.documentId}`);

    try {
        // Get the current end index
        const docInfo = await docs.documents.get({ documentId: args.documentId, fields: 'body(content(endIndex)),documentStyle(pageSize)' }); // Need content for endIndex
        let endIndex = 1;
        let lastCharIsNewline = false;
        if (docInfo.data.body?.content) {
            const lastElement = docInfo.data.body.content[docInfo.data.body.content.length - 1];
             if (lastElement?.endIndex) {
                endIndex = lastElement.endIndex -1; // Insert *before* the final newline of the doc typically
                // Crude check for last character (better check would involve reading last text run)
                 // const lastTextRun = ... find last text run ...
                 // if (lastTextRun?.content?.endsWith('\n')) lastCharIsNewline = true;
            }
        }
        // Simpler approach: Always assume insertion is needed unless explicitly told not to add newline
        const textToInsert = (args.addNewlineIfNeeded && endIndex > 1 ? '\n' : '') + args.textToAppend;

        if (!textToInsert) return "Nothing to append.";

        const request: docs_v1.Schema$Request = { insertText: { location: { index: endIndex }, text: textToInsert } };
        await GDocsHelpers.executeBatchUpdate(docs, args.documentId, [request]);

        log.info(`Successfully appended to doc: ${args.documentId}`);
        return `Successfully appended text to document ${args.documentId}.`;
    } catch (error: any) {
         log.error(`Error appending to doc ${args.documentId}: ${error.message || error}`);
         if (error instanceof UserError) throw error;
         if (error instanceof NotImplementedError) throw error;
         throw new UserError(`Failed to append to doc: ${error.message || 'Unknown error'}`);
    }

},
});

server.addTool({
name: 'insertText',
description: 'Inserts text at a specific index within the document body.',
parameters: DocumentIdParameter.extend({
textToInsert: z.string().min(1).describe('The text to insert.'),
index: z.number().int().min(1).describe('The index (1-based) where the text should be inserted.'),
}),
execute: async (args, { log }) => {
const docs = await getDocsClient();
log.info(`Inserting text in doc ${args.documentId} at index ${args.index}`);
try {
await GDocsHelpers.insertText(docs, args.documentId, args.textToInsert, args.index);
return `Successfully inserted text at index ${args.index}.`;
} catch (error: any) {
log.error(`Error inserting text in doc ${args.documentId}: ${error.message || error}`);
if (error instanceof UserError) throw error;
throw new UserError(`Failed to insert text: ${error.message || 'Unknown error'}`);
}
}
});

server.addTool({
name: 'deleteRange',
description: 'Deletes content within a specified range (start index inclusive, end index exclusive).',
parameters: DocumentIdParameter.extend({
  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"],
}),
execute: async (args, { log }) => {
const docs = await getDocsClient();
log.info(`Deleting range ${args.startIndex}-${args.endIndex} in doc ${args.documentId}`);
if (args.endIndex <= args.startIndex) {
throw new UserError("End index must be greater than start index for deletion.");
}
try {
const request: docs_v1.Schema$Request = {
                deleteContentRange: {
                    range: { startIndex: args.startIndex, endIndex: args.endIndex }
                }
            };
            await GDocsHelpers.executeBatchUpdate(docs, args.documentId, [request]);
            return `Successfully deleted content in range ${args.startIndex}-${args.endIndex}.`;
        } catch (error: any) {
            log.error(`Error deleting range in doc ${args.documentId}: ${error.message || error}`);
            if (error instanceof UserError) throw error;
            throw new UserError(`Failed to delete range: ${error.message || 'Unknown error'}`);
}
}
});

// --- Advanced Formatting & Styling Tools ---

server.addTool({
name: 'applyTextStyle',
description: 'Applies character-level formatting (bold, color, font, etc.) to a specific range or found text.',
parameters: ApplyTextStyleToolParameters,
execute: async (args: ApplyTextStyleToolArgs, { log }) => {
const docs = await getDocsClient();
let { startIndex, endIndex } = args.target as any; // Will be updated if target is text

        log.info(`Applying text style in doc ${args.documentId}. Target: ${JSON.stringify(args.target)}, Style: ${JSON.stringify(args.style)}`);

        try {
            // Determine target range
            if ('textToFind' in args.target) {
                const range = await GDocsHelpers.findTextRange(docs, args.documentId, args.target.textToFind, args.target.matchInstance);
                if (!range) {
                    throw new UserError(`Could not find instance ${args.target.matchInstance} of text "${args.target.textToFind}".`);
                }
                startIndex = range.startIndex;
                endIndex = range.endIndex;
                log.info(`Found text "${args.target.textToFind}" (instance ${args.target.matchInstance}) at range ${startIndex}-${endIndex}`);
            }

            if (startIndex === undefined || endIndex === undefined) {
                 throw new UserError("Target range could not be determined.");
            }
             if (endIndex <= startIndex) {
                 throw new UserError("End index must be greater than start index for styling.");
            }

            // Build the request
            const requestInfo = GDocsHelpers.buildUpdateTextStyleRequest(startIndex, endIndex, args.style);
            if (!requestInfo) {
                 return "No valid text styling options were provided.";
            }

            await GDocsHelpers.executeBatchUpdate(docs, args.documentId, [requestInfo.request]);
            return `Successfully applied text style (${requestInfo.fields.join(', ')}) to range ${startIndex}-${endIndex}.`;

        } catch (error: any) {
            log.error(`Error applying text style in doc ${args.documentId}: ${error.message || error}`);
            if (error instanceof UserError) throw error;
            if (error instanceof NotImplementedError) throw error; // Should not happen here
            throw new UserError(`Failed to apply text style: ${error.message || 'Unknown error'}`);
        }
    }

});

server.addTool({
name: 'applyParagraphStyle',
description: 'Applies paragraph-level formatting (alignment, spacing, named styles like Heading 1) to the paragraph(s) containing specific text, an index, or a range.',
parameters: ApplyParagraphStyleToolParameters,
execute: async (args: ApplyParagraphStyleToolArgs, { log }) => {
const docs = await getDocsClient();
let startIndex: number | undefined;
let endIndex: number | undefined;

        log.info(`Applying paragraph style to document ${args.documentId}`);
        log.info(`Style options: ${JSON.stringify(args.style)}`);
        log.info(`Target specification: ${JSON.stringify(args.target)}`);

        try {
            // STEP 1: Determine the target paragraph's range based on the targeting method
            if ('textToFind' in args.target) {
                // Find the text first
                log.info(`Finding text "${args.target.textToFind}" (instance ${args.target.matchInstance || 1})`);
                const textRange = await GDocsHelpers.findTextRange(
                    docs,
                    args.documentId,
                    args.target.textToFind,
                    args.target.matchInstance || 1
                );

                if (!textRange) {
                    throw new UserError(`Could not find "${args.target.textToFind}" in the document.`);
                }

                log.info(`Found text at range ${textRange.startIndex}-${textRange.endIndex}, now locating containing paragraph`);

                // Then find the paragraph containing this text
                const paragraphRange = await GDocsHelpers.getParagraphRange(
                    docs,
                    args.documentId,
                    textRange.startIndex
                );

                if (!paragraphRange) {
                    throw new UserError(`Found the text but could not determine the paragraph boundaries.`);
                }

                startIndex = paragraphRange.startIndex;
                endIndex = paragraphRange.endIndex;
                log.info(`Text is contained within paragraph at range ${startIndex}-${endIndex}`);

            } else if ('indexWithinParagraph' in args.target) {
                // Find paragraph containing the specified index
                log.info(`Finding paragraph containing index ${args.target.indexWithinParagraph}`);
                const paragraphRange = await GDocsHelpers.getParagraphRange(
                    docs,
                    args.documentId,
                    args.target.indexWithinParagraph
                );

                if (!paragraphRange) {
                    throw new UserError(`Could not find paragraph containing index ${args.target.indexWithinParagraph}.`);
                }

                startIndex = paragraphRange.startIndex;
                endIndex = paragraphRange.endIndex;
                log.info(`Located paragraph at range ${startIndex}-${endIndex}`);

            } else if ('startIndex' in args.target && 'endIndex' in args.target) {
                // Use directly provided range
                startIndex = args.target.startIndex;
                endIndex = args.target.endIndex;
                log.info(`Using provided paragraph range ${startIndex}-${endIndex}`);
            }

            // Verify that we have a valid range
            if (startIndex === undefined || endIndex === undefined) {
                throw new UserError("Could not determine target paragraph range from the provided information.");
            }

            if (endIndex <= startIndex) {
                throw new UserError(`Invalid paragraph range: end index (${endIndex}) must be greater than start index (${startIndex}).`);
            }

            // STEP 2: Build and apply the paragraph style request
            log.info(`Building paragraph style request for range ${startIndex}-${endIndex}`);
            const requestInfo = GDocsHelpers.buildUpdateParagraphStyleRequest(startIndex, endIndex, args.style);

            if (!requestInfo) {
                return "No valid paragraph styling options were provided.";
            }

            log.info(`Applying styles: ${requestInfo.fields.join(', ')}`);
            await GDocsHelpers.executeBatchUpdate(docs, args.documentId, [requestInfo.request]);

            return `Successfully applied paragraph styles (${requestInfo.fields.join(', ')}) to the paragraph.`;

        } catch (error: any) {
            // Detailed error logging
            log.error(`Error applying paragraph style in doc ${args.documentId}:`);
            log.error(error.stack || error.message || error);

            if (error instanceof UserError) throw error;
            if (error instanceof NotImplementedError) throw error;

            // Provide a more helpful error message
            throw new UserError(`Failed to apply paragraph style: ${error.message || 'Unknown error'}`);
        }
    }
});

// --- Structure & Content Tools ---

server.addTool({
name: 'insertTable',
description: 'Inserts a new table with the specified dimensions at a given index.',
parameters: DocumentIdParameter.extend({
rows: z.number().int().min(1).describe('Number of rows for the new table.'),
columns: z.number().int().min(1).describe('Number of columns for the new table.'),
index: z.number().int().min(1).describe('The index (1-based) where the table should be inserted.'),
}),
execute: async (args, { log }) => {
const docs = await getDocsClient();
log.info(`Inserting ${args.rows}x${args.columns} table in doc ${args.documentId} at index ${args.index}`);
try {
await GDocsHelpers.createTable(docs, args.documentId, args.rows, args.columns, args.index);
// The API response contains info about the created table, but might be too complex to return here.
return `Successfully inserted a ${args.rows}x${args.columns} table at index ${args.index}.`;
} catch (error: any) {
log.error(`Error inserting table in doc ${args.documentId}: ${error.message || error}`);
if (error instanceof UserError) throw error;
throw new UserError(`Failed to insert table: ${error.message || 'Unknown error'}`);
}
}
});

server.addTool({
name: 'editTableCell',
description: 'Edits the content and/or basic style of a specific table cell. Requires knowing table start index.',
parameters: DocumentIdParameter.extend({
tableStartIndex: z.number().int().min(1).describe("The starting index of the TABLE element itself (tricky to find, may require reading structure first)."),
rowIndex: z.number().int().min(0).describe("Row index (0-based)."),
columnIndex: z.number().int().min(0).describe("Column index (0-based)."),
textContent: z.string().optional().describe("Optional: New text content for the cell. Replaces existing content."),
// Combine basic styles for simplicity here. More advanced cell styling might need separate tools.
textStyle: TextStyleParameters.optional().describe("Optional: Text styles to apply."),
paragraphStyle: ParagraphStyleParameters.optional().describe("Optional: Paragraph styles (like alignment) to apply."),
// cellBackgroundColor: z.string().optional()... // Cell-specific styles are complex
}),
execute: async (args, { log }) => {
const docs = await getDocsClient();
log.info(`Editing cell (${args.rowIndex}, ${args.columnIndex}) in table starting at ${args.tableStartIndex}, doc ${args.documentId}`);

        // TODO: Implement complex logic
        // 1. Find the cell's content range based on tableStartIndex, rowIndex, columnIndex. This is NON-TRIVIAL.
        //    Requires getting the document, finding the table element, iterating through rows/cells to calculate indices.
        // 2. If textContent is provided, generate a DeleteContentRange request for the cell's current content.
        // 3. Generate an InsertText request for the new textContent at the cell's start index.
        // 4. If textStyle is provided, generate UpdateTextStyle requests for the new text range.
        // 5. If paragraphStyle is provided, generate UpdateParagraphStyle requests for the cell's paragraph range.
        // 6. Execute batch update.

        log.error("editTableCell is not implemented due to complexity of finding cell indices.");
        throw new NotImplementedError("Editing table cells is complex and not yet implemented.");
        // return `Edit request for cell (${args.rowIndex}, ${args.columnIndex}) submitted (Not Implemented).`;
    }

});

server.addTool({
name: 'insertPageBreak',
description: 'Inserts a page break at the specified index.',
parameters: DocumentIdParameter.extend({
index: z.number().int().min(1).describe('The index (1-based) where the page break should be inserted.'),
}),
execute: async (args, { log }) => {
const docs = await getDocsClient();
log.info(`Inserting page break in doc ${args.documentId} at index ${args.index}`);
try {
const request: docs_v1.Schema$Request = {
insertPageBreak: {
location: { index: args.index }
}
};
await GDocsHelpers.executeBatchUpdate(docs, args.documentId, [request]);
return `Successfully inserted page break at index ${args.index}.`;
} catch (error: any) {
log.error(`Error inserting page break in doc ${args.documentId}: ${error.message || error}`);
if (error instanceof UserError) throw error;
throw new UserError(`Failed to insert page break: ${error.message || 'Unknown error'}`);
}
}
});

// --- Image Insertion Tools ---

server.addTool({
name: 'insertImageFromUrl',
description: 'Inserts an inline image into a Google Document from a publicly accessible URL.',
parameters: DocumentIdParameter.extend({
imageUrl: z.string().url().describe('Publicly accessible URL to the image (must be http:// or https://).'),
index: z.number().int().min(1).describe('The index (1-based) where the image should be inserted.'),
width: z.number().min(1).optional().describe('Optional: Width of the image in points.'),
height: z.number().min(1).optional().describe('Optional: Height of the image in points.'),
}),
execute: async (args, { log }) => {
const docs = await getDocsClient();
log.info(`Inserting image from URL ${args.imageUrl} at index ${args.index} in doc ${args.documentId}`);

try {
await GDocsHelpers.insertInlineImage(
docs,
args.documentId,
args.imageUrl,
args.index,
args.width,
args.height
);

let sizeInfo = '';
if (args.width && args.height) {
sizeInfo = ` with size ${args.width}x${args.height}pt`;
}

return `Successfully inserted image from URL at index ${args.index}${sizeInfo}.`;
} catch (error: any) {
log.error(`Error inserting image in doc ${args.documentId}: ${error.message || error}`);
if (error instanceof UserError) throw error;
throw new UserError(`Failed to insert image: ${error.message || 'Unknown error'}`);
}
}
});

server.addTool({
name: 'insertLocalImage',
description: 'Uploads a local image file to Google Drive and inserts it into a Google Document. The image will be uploaded to the same folder as the document (or optionally to a specified folder).',
parameters: DocumentIdParameter.extend({
localImagePath: z.string().describe('Absolute path to the local image file (supports .jpg, .jpeg, .png, .gif, .bmp, .webp, .svg).'),
index: z.number().int().min(1).describe('The index (1-based) where the image should be inserted in the document.'),
width: z.number().min(1).optional().describe('Optional: Width of the image in points.'),
height: z.number().min(1).optional().describe('Optional: Height of the image in points.'),
uploadToSameFolder: z.boolean().optional().default(true).describe('If true, uploads the image to the same folder as the document. If false, uploads to Drive root.'),
}),
execute: async (args, { log }) => {
const docs = await getDocsClient();
const drive = await getDriveClient();
log.info(`Uploading local image ${args.localImagePath} and inserting at index ${args.index} in doc ${args.documentId}`);

try {
// Get the document's parent folder if requested
let parentFolderId: string | undefined;
if (args.uploadToSameFolder) {
try {
const docInfo = await drive.files.get({
fileId: args.documentId,
fields: 'parents'
});
if (docInfo.data.parents && docInfo.data.parents.length > 0) {
parentFolderId = docInfo.data.parents[0];
log.info(`Will upload image to document's parent folder: ${parentFolderId}`);
}
} catch (folderError) {
log.warn(`Could not determine document's parent folder, using Drive root: ${folderError}`);
}
}

// Upload the image to Drive
log.info(`Uploading image to Drive...`);
const imageUrl = await GDocsHelpers.uploadImageToDrive(
drive,
args.localImagePath,
parentFolderId
);
log.info(`Image uploaded successfully, public URL: ${imageUrl}`);

// Insert the image into the document
await GDocsHelpers.insertInlineImage(
docs,
args.documentId,
imageUrl,
args.index,
args.width,
args.height
);

let sizeInfo = '';
if (args.width && args.height) {
sizeInfo = ` with size ${args.width}x${args.height}pt`;
}

return `Successfully uploaded image to Drive and inserted it at index ${args.index}${sizeInfo}.\nImage URL: ${imageUrl}`;
} catch (error: any) {
log.error(`Error uploading/inserting local image in doc ${args.documentId}: ${error.message || error}`);
if (error instanceof UserError) throw error;
throw new UserError(`Failed to upload/insert local image: ${error.message || 'Unknown error'}`);
}
}
});

// --- Intelligent Assistance Tools (Examples/Stubs) ---

server.addTool({
name: 'fixListFormatting',
description: 'EXPERIMENTAL: Attempts to detect paragraphs that look like lists (e.g., starting with -, *, 1.) and convert them to proper Google Docs bulleted or numbered lists. Best used on specific sections.',
parameters: DocumentIdParameter.extend({
// Optional range to limit the scope, otherwise scans whole doc (potentially slow/risky)
range: OptionalRangeParameters.optional().describe("Optional: Limit the fixing process to a specific range.")
}),
execute: async (args, { log }) => {
const docs = await getDocsClient();
log.warn(`Executing EXPERIMENTAL fixListFormatting for doc ${args.documentId}. Range: ${JSON.stringify(args.range)}`);
try {
await GDocsHelpers.detectAndFormatLists(docs, args.documentId, args.range?.startIndex, args.range?.endIndex);
return `Attempted to fix list formatting. Please review the document for accuracy.`;
} catch (error: any) {
log.error(`Error fixing list formatting in doc ${args.documentId}: ${error.message || error}`);
if (error instanceof UserError) throw error;
if (error instanceof NotImplementedError) throw error; // Expected if helper not implemented
throw new UserError(`Failed to fix list formatting: ${error.message || 'Unknown error'}`);
}
}
});

// === COMMENT TOOLS ===

server.addTool({
  name: 'listComments',
  description: 'Lists all comments in a Google Document.',
  parameters: DocumentIdParameter,
  execute: async (args, { log }) => {
    log.info(`Listing comments for document ${args.documentId}`);
    const docsClient = await getDocsClient();
    const driveClient = await getDriveClient();
    
    try {
      // First get the document to have context
      const doc = await docsClient.documents.get({ documentId: args.documentId });
      
      // Use Drive API v3 with proper fields to get quoted content
      const drive = google.drive({ version: 'v3', auth: authClient! });
      const response = await drive.comments.list({
        fileId: args.documentId,
        fields: 'comments(id,content,quotedFileContent,author,createdTime,resolved)',
        pageSize: 100
      });
      
      const comments = response.data.comments || [];
      
      if (comments.length === 0) {
        return 'No comments found in this document.';
      }
      
      // Format comments for display
      const formattedComments = comments.map((comment: any, index: number) => {
        const replies = comment.replies?.length || 0;
        const status = comment.resolved ? ' [RESOLVED]' : '';
        const author = comment.author?.displayName || 'Unknown';
        const date = comment.createdTime ? new Date(comment.createdTime).toLocaleDateString() : 'Unknown date';
        
        // Get the actual quoted text content
        const quotedText = comment.quotedFileContent?.value || 'No quoted text';
        const anchor = quotedText !== 'No quoted text' ? ` (anchored to: "${quotedText.substring(0, 100)}${quotedText.length > 100 ? '...' : ''}")` : '';
        
        let result = `\n${index + 1}. **${author}** (${date})${status}${anchor}\n   ${comment.content}`;
        
        if (replies > 0) {
          result += `\n   └─ ${replies} ${replies === 1 ? 'reply' : 'replies'}`;
        }
        
        result += `\n   Comment ID: ${comment.id}`;
        
        return result;
      }).join('\n');
      
      return `Found ${comments.length} comment${comments.length === 1 ? '' : 's'}:\n${formattedComments}`;
      
    } catch (error: any) {
      log.error(`Error listing comments: ${error.message || error}`);
      throw new UserError(`Failed to list comments: ${error.message || 'Unknown error'}`);
    }
  }
});

server.addTool({
  name: 'getComment',
  description: 'Gets a specific comment with its full thread of replies.',
  parameters: DocumentIdParameter.extend({
    commentId: z.string().describe('The ID of the comment to retrieve')
  }),
  execute: async (args, { log }) => {
    log.info(`Getting comment ${args.commentId} from document ${args.documentId}`);
    
    try {
      const drive = google.drive({ version: 'v3', auth: authClient! });
      const response = await drive.comments.get({
        fileId: args.documentId,
        commentId: args.commentId,
        fields: 'id,content,quotedFileContent,author,createdTime,resolved,replies(id,content,author,createdTime)'
      });
      
      const comment = response.data;
      const author = comment.author?.displayName || 'Unknown';
      const date = comment.createdTime ? new Date(comment.createdTime).toLocaleDateString() : 'Unknown date';
      const status = comment.resolved ? ' [RESOLVED]' : '';
      const quotedText = comment.quotedFileContent?.value || 'No quoted text';
      const anchor = quotedText !== 'No quoted text' ? `\nAnchored to: "${quotedText}"` : '';
      
      let result = `**${author}** (${date})${status}${anchor}\n${comment.content}`;
      
      // Add replies if any
      if (comment.replies && comment.replies.length > 0) {
        result += '\n\n**Replies:**';
        comment.replies.forEach((reply: any, index: number) => {
          const replyAuthor = reply.author?.displayName || 'Unknown';
          const replyDate = reply.createdTime ? new Date(reply.createdTime).toLocaleDateString() : 'Unknown date';
          result += `\n${index + 1}. **${replyAuthor}** (${replyDate})\n   ${reply.content}`;
        });
      }
      
      return result;
      
    } catch (error: any) {
      log.error(`Error getting comment: ${error.message || error}`);
      throw new UserError(`Failed to get comment: ${error.message || 'Unknown error'}`);
    }
  }
});

server.addTool({
  name: 'addComment',
  description: 'Adds a comment anchored to a specific text range in the document.',
  parameters: DocumentIdParameter.extend({
    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).'),
    commentText: z.string().min(1).describe('The content of the comment.'),
  }).refine(data => data.endIndex > data.startIndex, {
    message: 'endIndex must be greater than startIndex',
    path: ['endIndex'],
  }),
  execute: async (args, { log }) => {
    log.info(`Adding comment to range ${args.startIndex}-${args.endIndex} in doc ${args.documentId}`);
    
    try {
      // First, get the text content that will be quoted
      const docsClient = await getDocsClient();
      const doc = await docsClient.documents.get({ documentId: args.documentId });
      
      // Extract the quoted text from the document
      let quotedText = '';
      const content = doc.data.body?.content || [];
      
      for (const element of content) {
        if (element.paragraph) {
          const elements = element.paragraph.elements || [];
          for (const textElement of elements) {
            if (textElement.textRun) {
              const elementStart = textElement.startIndex || 0;
              const elementEnd = textElement.endIndex || 0;
              
              // Check if this element overlaps with our range
              if (elementEnd > args.startIndex && elementStart < args.endIndex) {
                const text = textElement.textRun.content || '';
                const startOffset = Math.max(0, args.startIndex - elementStart);
                const endOffset = Math.min(text.length, args.endIndex - elementStart);
                quotedText += text.substring(startOffset, endOffset);
              }
            }
          }
        }
      }
      
      // Use Drive API v3 for comments
      const drive = google.drive({ version: 'v3', auth: authClient! });
      
      const response = await drive.comments.create({
        fileId: args.documentId,
        fields: 'id,content,quotedFileContent,author,createdTime,resolved',
        requestBody: {
          content: args.commentText,
          quotedFileContent: {
            value: quotedText,
            mimeType: 'text/html'
          },
          anchor: JSON.stringify({
            r: args.documentId,
            a: [{
              txt: {
                o: args.startIndex - 1,  // Drive API uses 0-based indexing
                l: args.endIndex - args.startIndex,
                ml: args.endIndex - args.startIndex
              }
            }]
          })
        }
      });
      
      return `Comment added successfully. Comment ID: ${response.data.id}`;
      
    } catch (error: any) {
      log.error(`Error adding comment: ${error.message || error}`);
      throw new UserError(`Failed to add comment: ${error.message || 'Unknown error'}`);
    }
  }
});

server.addTool({
  name: 'replyToComment',
  description: 'Adds a reply to an existing comment.',
  parameters: DocumentIdParameter.extend({
    commentId: z.string().describe('The ID of the comment to reply to'),
    replyText: z.string().min(1).describe('The content of the reply')
  }),
  execute: async (args, { log }) => {
    log.info(`Adding reply to comment ${args.commentId} in doc ${args.documentId}`);
    
    try {
      const drive = google.drive({ version: 'v3', auth: authClient! });
      
      const response = await drive.replies.create({
        fileId: args.documentId,
        commentId: args.commentId,
        fields: 'id,content,author,createdTime',
        requestBody: {
          content: args.replyText
        }
      });
      
      return `Reply added successfully. Reply ID: ${response.data.id}`;
      
    } catch (error: any) {
      log.error(`Error adding reply: ${error.message || error}`);
      throw new UserError(`Failed to add reply: ${error.message || 'Unknown error'}`);
    }
  }
});

server.addTool({
  name: 'resolveComment',
  description: 'Marks a comment as resolved.',
  parameters: DocumentIdParameter.extend({
    commentId: z.string().describe('The ID of the comment to resolve')
  }),
  execute: async (args, { log }) => {
    log.info(`Resolving comment ${args.commentId} in doc ${args.documentId}`);
    
    try {
      const drive = google.drive({ version: 'v3', auth: authClient! });
      
      await drive.comments.update({
        fileId: args.documentId,
        commentId: args.commentId,
        requestBody: {
          resolved: true
        }
      });
      
      return `Comment ${args.commentId} has been resolved.`;
      
    } catch (error: any) {
      log.error(`Error resolving comment: ${error.message || error}`);
      throw new UserError(`Failed to resolve comment: ${error.message || 'Unknown error'}`);
    }
  }
});

server.addTool({
  name: 'deleteComment',
  description: 'Deletes a comment from the document.',
  parameters: DocumentIdParameter.extend({
    commentId: z.string().describe('The ID of the comment to delete')
  }),
  execute: async (args, { log }) => {
    log.info(`Deleting comment ${args.commentId} from doc ${args.documentId}`);
    
    try {
      const drive = google.drive({ version: 'v3', auth: authClient! });
      
      await drive.comments.delete({
        fileId: args.documentId,
        commentId: args.commentId
      });
      
      return `Comment ${args.commentId} has been deleted.`;
      
    } catch (error: any) {
      log.error(`Error deleting comment: ${error.message || error}`);
      throw new UserError(`Failed to delete comment: ${error.message || 'Unknown error'}`);
    }
  }
});

// --- Add Stubs for other advanced features ---
// (findElement, getDocumentMetadata, replaceText, list management, image handling, section breaks, footnotes, etc.)
// Example Stub:
server.addTool({
name: 'findElement',
description: 'Finds elements (paragraphs, tables, etc.) based on various criteria. (Not Implemented)',
parameters: DocumentIdParameter.extend({
// Define complex query parameters...
textQuery: z.string().optional(),
elementType: z.enum(['paragraph', 'table', 'list', 'image']).optional(),
// styleQuery...
}),
execute: async (args, { log }) => {
log.warn("findElement tool called but is not implemented.");
throw new NotImplementedError("Finding elements by complex criteria is not yet implemented.");
}
});

// --- Preserve the existing formatMatchingText tool for backward compatibility ---
server.addTool({
name: 'formatMatchingText',
description: 'Finds specific text within a Google Document and applies character formatting (bold, italics, color, etc.) to the specified instance.',
parameters: z.object({
  documentId: z.string().describe('The ID of the Google Document.'),
  textToFind: z.string().min(1).describe('The exact text string to find and format.'),
  matchInstance: z.number().int().min(1).optional().default(1).describe('Which instance of the text to format (1st, 2nd, etc.). Defaults to 1.'),
  // Re-use optional Formatting Parameters (SHARED)
  bold: z.boolean().optional().describe('Apply bold formatting.'),
  italic: z.boolean().optional().describe('Apply italic formatting.'),
  underline: z.boolean().optional().describe('Apply underline formatting.'),
  strikethrough: z.boolean().optional().describe('Apply strikethrough formatting.'),
  fontSize: z.number().min(1).optional().describe('Set font size (in points, e.g., 12).'),
  fontFamily: z.string().optional().describe('Set font family (e.g., "Arial", "Times New Roman").'),
  foregroundColor: z.string()
    .refine((color) => /^#?([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/.test(color), {
      message: "Invalid hex color format (e.g., #FF0000 or #F00)"
    })
    .optional()
    .describe('Set text color using hex format (e.g., "#FF0000").'),
  backgroundColor: z.string()
    .refine((color) => /^#?([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/.test(color), {
      message: "Invalid hex color format (e.g., #00FF00 or #0F0)"
    })
    .optional()
    .describe('Set text background color using hex format (e.g., "#FFFF00").'),
  linkUrl: z.string().url().optional().describe('Make the text a hyperlink pointing to this URL.')
})
.refine(data => Object.keys(data).some(key => !['documentId', 'textToFind', 'matchInstance'].includes(key) && data[key as keyof typeof data] !== undefined), {
    message: "At least one formatting option (bold, italic, fontSize, etc.) must be provided."
}),
execute: async (args, { log }) => {
  // Adapt to use the new applyTextStyle implementation under the hood
  const docs = await getDocsClient();
  log.info(`Using formatMatchingText (legacy) for doc ${args.documentId}, target: "${args.textToFind}" (instance ${args.matchInstance})`);

  try {
    // Extract the style parameters
    const styleParams: TextStyleArgs = {};
    if (args.bold !== undefined) styleParams.bold = args.bold;
    if (args.italic !== undefined) styleParams.italic = args.italic;
    if (args.underline !== undefined) styleParams.underline = args.underline;
    if (args.strikethrough !== undefined) styleParams.strikethrough = args.strikethrough;
    if (args.fontSize !== undefined) styleParams.fontSize = args.fontSize;
    if (args.fontFamily !== undefined) styleParams.fontFamily = args.fontFamily;
    if (args.foregroundColor !== undefined) styleParams.foregroundColor = args.foregroundColor;
    if (args.backgroundColor !== undefined) styleParams.backgroundColor = args.backgroundColor;
    if (args.linkUrl !== undefined) styleParams.linkUrl = args.linkUrl;

    // Find the text range
    const range = await GDocsHelpers.findTextRange(docs, args.documentId, args.textToFind, args.matchInstance);
    if (!range) {
      throw new UserError(`Could not find instance ${args.matchInstance} of text "${args.textToFind}".`);
    }

    // Build and execute the request
    const requestInfo = GDocsHelpers.buildUpdateTextStyleRequest(range.startIndex, range.endIndex, styleParams);
    if (!requestInfo) {
      return "No valid text styling options were provided.";
    }

    await GDocsHelpers.executeBatchUpdate(docs, args.documentId, [requestInfo.request]);
    return `Successfully applied formatting to instance ${args.matchInstance} of "${args.textToFind}".`;
  } catch (error: any) {
    log.error(`Error in formatMatchingText for doc ${args.documentId}: ${error.message || error}`);
    if (error instanceof UserError) throw error;
    throw new UserError(`Failed to format text: ${error.message || 'Unknown error'}`);
  }
}
});

// === GOOGLE DRIVE TOOLS ===

server.addTool({
name: 'listGoogleDocs',
description: 'Lists Google Documents from your Google Drive with optional filtering.',
parameters: z.object({
  maxResults: z.number().int().min(1).max(100).optional().default(20).describe('Maximum number of documents to return (1-100).'),
  query: z.string().optional().describe('Search query to filter documents by name or content.'),
  orderBy: z.enum(['name', 'modifiedTime', 'createdTime']).optional().default('modifiedTime').describe('Sort order for results.'),
}),
execute: async (args, { log }) => {
const drive = await getDriveClient();
log.info(`Listing Google Docs. Query: ${args.query || 'none'}, Max: ${args.maxResults}, Order: ${args.orderBy}`);

try {
  // Build the query string for Google Drive API
  let queryString = "mimeType='application/vnd.google-apps.document' and trashed=false";
  if (args.query) {
    queryString += ` and (name contains '${args.query}' or fullText contains '${args.query}')`;
  }

  const response = await drive.files.list({
    q: queryString,
    pageSize: args.maxResults,
    orderBy: args.orderBy === 'name' ? 'name' : args.orderBy,
    fields: 'files(id,name,modifiedTime,createdTime,size,webViewLink,owners(displayName,emailAddress))',
  });

  const files = response.data.files || [];

  if (files.length === 0) {
    return "No Google Docs found matching your criteria.";
  }

  let result = `Found ${files.length} Google Document(s):\n\n`;
  files.forEach((file, index) => {
    const modifiedDate = file.modifiedTime ? new Date(file.modifiedTime).toLocaleDateString() : 'Unknown';
    const owner = file.owners?.[0]?.displayName || 'Unknown';
    result += `${index + 1}. **${file.name}**\n`;
    result += `   ID: ${file.id}\n`;
    result += `   Modified: ${modifiedDate}\n`;
    result += `   Owner: ${owner}\n`;
    result += `   Link: ${file.webViewLink}\n\n`;
  });

  return result;
} catch (error: any) {
  log.error(`Error listing Google Docs: ${error.message || error}`);
  if (error.code === 403) throw new UserError("Permission denied. Make sure you have granted Google Drive access to the application.");
  throw new UserError(`Failed to list documents: ${error.message || 'Unknown error'}`);
}
}
});

server.addTool({
name: 'searchGoogleDocs',
description: 'Searches for Google Documents by name, content, or other criteria.',
parameters: z.object({
  searchQuery: z.string().min(1).describe('Search term to find in document names or content.'),
  searchIn: z.enum(['name', 'content', 'both']).optional().default('both').describe('Where to search: document names, content, or both.'),
  maxResults: z.number().int().min(1).max(50).optional().default(10).describe('Maximum number of results to return.'),
  modifiedAfter: z.string().optional().describe('Only return documents modified after this date (ISO 8601 format, e.g., "2024-01-01").'),
}),
execute: async (args, { log }) => {
const drive = await getDriveClient();
log.info(`Searching Google Docs for: "${args.searchQuery}" in ${args.searchIn}`);

try {
  let queryString = "mimeType='application/vnd.google-apps.document' and trashed=false";

  // Add search criteria
  if (args.searchIn === 'name') {
    queryString += ` and name contains '${args.searchQuery}'`;
  } else if (args.searchIn === 'content') {
    queryString += ` and fullText contains '${args.searchQuery}'`;
  } else {
    queryString += ` and (name contains '${args.searchQuery}' or fullText contains '${args.searchQuery}')`;
  }

  // Add date filter if provided
  if (args.modifiedAfter) {
    queryString += ` and modifiedTime > '${args.modifiedAfter}'`;
  }

  const response = await drive.files.list({
    q: queryString,
    pageSize: args.maxResults,
    orderBy: 'modifiedTime desc',
    fields: 'files(id,name,modifiedTime,createdTime,webViewLink,owners(displayName),parents)',
  });

  const files = response.data.files || [];

  if (files.length === 0) {
    return `No Google Docs found containing "${args.searchQuery}".`;
  }

  let result = `Found ${files.length} document(s) matching "${args.searchQuery}":\n\n`;
  files.forEach((file, index) => {
    const modifiedDate = file.modifiedTime ? new Date(file.modifiedTime).toLocaleDateString() : 'Unknown';
    const owner = file.owners?.[0]?.displayName || 'Unknown';
    result += `${index + 1}. **${file.name}**\n`;
    result += `   ID: ${file.id}\n`;
    result += `   Modified: ${modifiedDate}\n`;
    result += `   Owner: ${owner}\n`;
    result += `   Link: ${file.webViewLink}\n\n`;
  });

  return result;
} catch (error: any) {
  log.error(`Error searching Google Docs: ${error.message || error}`);
  if (error.code === 403) throw new UserError("Permission denied. Make sure you have granted Google Drive access to the application.");
  throw new UserError(`Failed to search documents: ${error.message || 'Unknown error'}`);
}
}
});

server.addTool({
name: 'getRecentGoogleDocs',
description: 'Gets the most recently modified Google Documents.',
parameters: z.object({
  maxResults: z.number().int().min(1).max(50).optional().default(10).describe('Maximum number of recent documents to return.'),
  daysBack: z.number().int().min(1).max(365).optional().default(30).describe('Only show documents modified within this many days.'),
}),
execute: async (args, { log }) => {
const drive = await getDriveClient();
log.info(`Getting recent Google Docs: ${args.maxResults} results, ${args.daysBack} days back`);

try {
  const cutoffDate = new Date();
  cutoffDate.setDate(cutoffDate.getDate() - args.daysBack);
  const cutoffDateStr = cutoffDate.toISOString();

  const queryString = `mimeType='application/vnd.google-apps.document' and trashed=false and modifiedTime > '${cutoffDateStr}'`;

  const response = await drive.files.list({
    q: queryString,
    pageSize: args.maxResults,
    orderBy: 'modifiedTime desc',
    fields: 'files(id,name,modifiedTime,createdTime,webViewLink,owners(displayName),lastModifyingUser(displayName))',
  });

  const files = response.data.files || [];

  if (files.length === 0) {
    return `No Google Docs found that were modified in the last ${args.daysBack} days.`;
  }

  let result = `${files.length} recently modified Google Document(s) (last ${args.daysBack} days):\n\n`;
  files.forEach((file, index) => {
    const modifiedDate = file.modifiedTime ? new Date(file.modifiedTime).toLocaleString() : 'Unknown';
    const lastModifier = file.lastModifyingUser?.displayName || 'Unknown';
    const owner = file.owners?.[0]?.displayName || 'Unknown';

    result += `${index + 1}. **${file.name}**\n`;
    result += `   ID: ${file.id}\n`;
    result += `   Last Modified: ${modifiedDate} by ${lastModifier}\n`;
    result += `   Owner: ${owner}\n`;
    result += `   Link: ${file.webViewLink}\n\n`;
  });

  return result;
} catch (error: any) {
  log.error(`Error getting recent Google Docs: ${error.message || error}`);
  if (error.code === 403) throw new UserError("Permission denied. Make sure you have granted Google Drive access to the application.");
  throw new UserError(`Failed to get recent documents: ${error.message || 'Unknown error'}`);
}
}
});

server.addTool({
name: 'getDocumentInfo',
description: 'Gets detailed information about a specific Google Document.',
parameters: DocumentIdParameter,
execute: async (args, { log }) => {
const drive = await getDriveClient();
log.info(`Getting info for document: ${args.documentId}`);

try {
  const response = await drive.files.get({
    fileId: args.documentId,
    fields: 'id,name,description,mimeType,size,createdTime,modifiedTime,webViewLink,alternateLink,owners(displayName,emailAddress),lastModifyingUser(displayName,emailAddress),shared,permissions(role,type,emailAddress),parents,version',
  });

  const file = response.data;

  if (!file) {
    throw new UserError(`Document with ID ${args.documentId} not found.`);
  }

  const createdDate = file.createdTime ? new Date(file.createdTime).toLocaleString() : 'Unknown';
  const modifiedDate = file.modifiedTime ? new Date(file.modifiedTime).toLocaleString() : 'Unknown';
  const owner = file.owners?.[0];
  const lastModifier = file.lastModifyingUser;

  let result = `**Document Information:**\n\n`;
  result += `**Name:** ${file.name}\n`;
  result += `**ID:** ${file.id}\n`;
  result += `**Type:** Google Document\n`;
  result += `**Created:** ${createdDate}\n`;
  result += `**Last Modified:** ${modifiedDate}\n`;

  if (owner) {
    result += `**Owner:** ${owner.displayName} (${owner.emailAddress})\n`;
  }

  if (lastModifier) {
    result += `**Last Modified By:** ${lastModifier.displayName} (${lastModifier.emailAddress})\n`;
  }

  result += `**Shared:** ${file.shared ? 'Yes' : 'No'}\n`;
  result += `**View Link:** ${file.webViewLink}\n`;

  if (file.description) {
    result += `**Description:** ${file.description}\n`;
  }

  return result;
} catch (error: any) {
  log.error(`Error getting document info: ${error.message || error}`);
  if (error.code === 404) throw new UserError(`Document not found (ID: ${args.documentId}).`);
  if (error.code === 403) throw new UserError("Permission denied. Make sure you have access to this document.");
  throw new UserError(`Failed to get document info: ${error.message || 'Unknown error'}`);
}
}
});

// === GOOGLE DRIVE FILE MANAGEMENT TOOLS ===

// --- Folder Management Tools ---

server.addTool({
name: 'createFolder',
description: 'Creates a new folder in Google Drive.',
parameters: z.object({
  name: z.string().min(1).describe('Name for the new folder.'),
  parentFolderId: z.string().optional().describe('Parent folder ID. If not provided, creates folder in Drive root.'),
}),
execute: async (args, { log }) => {
const drive = await getDriveClient();
log.info(`Creating folder "${args.name}" ${args.parentFolderId ? `in parent ${args.parentFolderId}` : 'in root'}`);

try {
  const folderMetadata: drive_v3.Schema$File = {
    name: args.name,
    mimeType: 'application/vnd.google-apps.folder',
  };

  if (args.parentFolderId) {
    folderMetadata.parents = [args.parentFolderId];
  }

  const response = await drive.files.create({
    requestBody: folderMetadata,
    fields: 'id,name,parents,webViewLink',
  });

  const folder = response.data;
  return `Successfully created folder "${folder.name}" (ID: ${folder.id})\nLink: ${folder.webViewLink}`;
} catch (error: any) {
  log.error(`Error creating folder: ${error.message || error}`);
  if (error.code === 404) throw new UserError("Parent folder not found. Check the parent folder ID.");
  if (error.code === 403) throw new UserError("Permission denied. Make sure you have write access to the parent folder.");
  throw new UserError(`Failed to create folder: ${error.message || 'Unknown error'}`);
}
}
});

server.addTool({
name: 'listFolderContents',
description: 'Lists the contents of a specific folder in Google Drive.',
parameters: z.object({
  folderId: z.string().describe('ID of the folder to list contents of. Use "root" for the root Drive folder.'),
  includeSubfolders: z.boolean().optional().default(true).describe('Whether to include subfolders in results.'),
  includeFiles: z.boolean().optional().default(true).describe('Whether to include files in results.'),
  maxResults: z.number().int().min(1).max(100).optional().default(50).describe('Maximum number of items to return.'),
}),
execute: async (args, { log }) => {
const drive = await getDriveClient();
log.info(`Listing contents of folder: ${args.folderId}`);

try {
  let queryString = `'${args.folderId}' in parents and trashed=false`;

  // Filter by type if specified
  if (!args.includeSubfolders && !args.includeFiles) {
    throw new UserError("At least one of includeSubfolders or includeFiles must be true.");
  }

  if (!args.includeSubfolders) {
    queryString += ` and mimeType!='application/vnd.google-apps.folder'`;
  } else if (!args.includeFiles) {
    queryString += ` and mimeType='application/vnd.google-apps.folder'`;
  }

  const response = await drive.files.list({
    q: queryString,
    pageSize: args.maxResults,
    orderBy: 'folder,name',
    fields: 'files(id,name,mimeType,size,modifiedTime,webViewLink,owners(displayName))',
  });

  const items = response.data.files || [];

  if (items.length === 0) {
    return "The folder is empty or you don't have permission to view its contents.";
  }

  let result = `Contents of folder (${items.length} item${items.length !== 1 ? 's' : ''}):\n\n`;

  // Separate folders and files
  const folders = items.filter(item => item.mimeType === 'application/vnd.google-apps.folder');
  const files = items.filter(item => item.mimeType !== 'application/vnd.google-apps.folder');

  // List folders first
  if (folders.length > 0 && args.includeSubfolders) {
    result += `**Folders (${folders.length}):**\n`;
    folders.forEach(folder => {
      result += `📁 ${folder.name} (ID: ${folder.id})\n`;
    });
    result += '\n';
  }

  // Then list files
  if (files.length > 0 && args.includeFiles) {
    result += `**Files (${files.length}):\n`;
    files.forEach(file => {
      const fileType = file.mimeType === 'application/vnd.google-apps.document' ? '📄' :
                      file.mimeType === 'application/vnd.google-apps.spreadsheet' ? '📊' :
                      file.mimeType === 'application/vnd.google-apps.presentation' ? '📈' : '📎';
      const modifiedDate = file.modifiedTime ? new Date(file.modifiedTime).toLocaleDateString() : 'Unknown';
      const owner = file.owners?.[0]?.displayName || 'Unknown';

      result += `${fileType} ${file.name}\n`;
      result += `   ID: ${file.id}\n`;
      result += `   Modified: ${modifiedDate} by ${owner}\n`;
      result += `   Link: ${file.webViewLink}\n\n`;
    });
  }

  return result;
} catch (error: any) {
  log.error(`Error listing folder contents: ${error.message || error}`);
  if (error.code === 404) throw new UserError("Folder not found. Check the folder ID.");
  if (error.code === 403) throw new UserError("Permission denied. Make sure you have access to this folder.");
  throw new UserError(`Failed to list folder contents: ${error.message || 'Unknown error'}`);
}
}
});

server.addTool({
name: 'getFolderInfo',
description: 'Gets detailed information about a specific folder in Google Drive.',
parameters: z.object({
  folderId: z.string().describe('ID of the folder to get information about.'),
}),
execute: async (args, { log }) => {
const drive = await getDriveClient();
log.info(`Getting folder info: ${args.folderId}`);

try {
  const response = await drive.files.get({
    fileId: args.folderId,
    fields: 'id,name,description,createdTime,modifiedTime,webViewLink,owners(displayName,emailAddress),lastModifyingUser(displayName),shared,parents',
  });

  const folder = response.data;

  if (folder.mimeType !== 'application/vnd.google-apps.folder') {
    throw new UserError("The specified ID does not belong to a folder.");
  }

  const createdDate = folder.createdTime ? new Date(folder.createdTime).toLocaleString() : 'Unknown';
  const modifiedDate = folder.modifiedTime ? new Date(folder.modifiedTime).toLocaleString() : 'Unknown';
  const owner = folder.owners?.[0];
  const lastModifier = folder.lastModifyingUser;

  let result = `**Folder Information:**\n\n`;
  result += `**Name:** ${folder.name}\n`;
  result += `**ID:** ${folder.id}\n`;
  result += `**Created:** ${createdDate}\n`;
  result += `**Last Modified:** ${modifiedDate}\n`;

  if (owner) {
    result += `**Owner:** ${owner.displayName} (${owner.emailAddress})\n`;
  }

  if (lastModifier) {
    result += `**Last Modified By:** ${lastModifier.displayName}\n`;
  }

  result += `**Shared:** ${folder.shared ? 'Yes' : 'No'}\n`;
  result += `**View Link:** ${folder.webViewLink}\n`;

  if (folder.description) {
    result += `**Description:** ${folder.description}\n`;
  }

  if (folder.parents && folder.parents.length > 0) {
    result += `**Parent Folder ID:** ${folder.parents[0]}\n`;
  }

  return result;
} catch (error: any) {
  log.error(`Error getting folder info: ${error.message || error}`);
  if (error.code === 404) throw new UserError(`Folder not found (ID: ${args.folderId}).`);
  if (error.code === 403) throw new UserError("Permission denied. Make sure you have access to this folder.");
  throw new UserError(`Failed to get folder info: ${error.message || 'Unknown error'}`);
}
}
});

// --- File Operation Tools ---

server.addTool({
name: 'moveFile',
description: 'Moves a file or folder to a different location in Google Drive.',
parameters: z.object({
  fileId: z.string().describe('ID of the file or folder to move.'),
  newParentId: z.string().describe('ID of the destination folder. Use "root" for Drive root.'),
  removeFromAllParents: z.boolean().optional().default(false).describe('If true, removes from all current parents. If false, adds to new parent while keeping existing parents.'),
}),
execute: async (args, { log }) => {
const drive = await getDriveClient();
log.info(`Moving file ${args.fileId} to folder ${args.newParentId}`);

try {
  // First get the current parents
  const fileInfo = await drive.files.get({
    fileId: args.fileId,
    fields: 'name,parents',
  });

  const fileName = fileInfo.data.name;
  const currentParents = fileInfo.data.parents || [];

  let updateParams: any = {
    fileId: args.fileId,
    addParents: args.newParentId,
    fields: 'id,name,parents',
  };

  if (args.removeFromAllParents && currentParents.length > 0) {
    updateParams.removeParents = currentParents.join(',');
  }

  const response = await drive.files.update(updateParams);

  const action = args.removeFromAllParents ? 'moved' : 'copied';
  return `Successfully ${action} "${fileName}" to new location.\nFile ID: ${response.data.id}`;
} catch (error: any) {
  log.error(`Error moving file: ${error.message || error}`);
  if (error.code === 404) throw new UserError("File or destination folder not found. Check the IDs.");
  if (error.code === 403) throw new UserError("Permission denied. Make sure you have write access to both source and destination.");
  throw new UserError(`Failed to move file: ${error.message || 'Unknown error'}`);
}
}
});

server.addTool({
name: 'copyFile',
description: 'Creates a copy of a Google Drive file or document.',
parameters: z.object({
  fileId: z.string().describe('ID of the file to copy.'),
  newName: z.string().optional().describe('Name for the copied file. If not provided, will use "Copy of [original name]".'),
  parentFolderId: z.string().optional().describe('ID of folder where copy should be placed. If not provided, places in same location as original.'),
}),
execute: async (args, { log }) => {
const drive = await getDriveClient();
log.info(`Copying file ${args.fileId} ${args.newName ? `as "${args.newName}"` : ''}`);

try {
  // Get original file info
  const originalFile = await drive.files.get({
    fileId: args.fileId,
    fields: 'name,parents',
  });

  const copyMetadata: drive_v3.Schema$File = {
    name: args.newName || `Copy of ${originalFile.data.name}`,
  };

  if (args.parentFolderId) {
    copyMetadata.parents = [args.parentFolderId];
  } else if (originalFile.data.parents) {
    copyMetadata.parents = originalFile.data.parents;
  }

  const response = await drive.files.copy({
    fileId: args.fileId,
    requestBody: copyMetadata,
    fields: 'id,name,webViewLink',
  });

  const copiedFile = response.data;
  return `Successfully created copy "${copiedFile.name}" (ID: ${copiedFile.id})\nLink: ${copiedFile.webViewLink}`;
} catch (error: any) {
  log.error(`Error copying file: ${error.message || error}`);
  if (error.code === 404) throw new UserError("Original file or destination folder not found. Check the IDs.");
  if (error.code === 403) throw new UserError("Permission denied. Make sure you have read access to the original file and write access to the destination.");
  throw new UserError(`Failed to copy file: ${error.message || 'Unknown error'}`);
}
}
});

server.addTool({
name: 'renameFile',
description: 'Renames a file or folder in Google Drive.',
parameters: z.object({
  fileId: z.string().describe('ID of the file or folder to rename.'),
  newName: z.string().min(1).describe('New name for the file or folder.'),
}),
execute: async (args, { log }) => {
const drive = await getDriveClient();
log.info(`Renaming file ${args.fileId} to "${args.newName}"`);

try {
  const response = await drive.files.update({
    fileId: args.fileId,
    requestBody: {
      name: args.newName,
    },
    fields: 'id,name,webViewLink',
  });

  const file = response.data;
  return `Successfully renamed to "${file.name}" (ID: ${file.id})\nLink: ${file.webViewLink}`;
} catch (error: any) {
  log.error(`Error renaming file: ${error.message || error}`);
  if (error.code === 404) throw new UserError("File not found. Check the file ID.");
  if (error.code === 403) throw new UserError("Permission denied. Make sure you have write access to this file.");
  throw new UserError(`Failed to rename file: ${error.message || 'Unknown error'}`);
}
}
});

server.addTool({
name: 'deleteFile',
description: 'Permanently deletes a file or folder from Google Drive.',
parameters: z.object({
  fileId: z.string().describe('ID of the file or folder to delete.'),
  skipTrash: z.boolean().optional().default(false).describe('If true, permanently deletes the file. If false, moves to trash (can be restored).'),
}),
execute: async (args, { log }) => {
const drive = await getDriveClient();
log.info(`Deleting file ${args.fileId} ${args.skipTrash ? '(permanent)' : '(to trash)'}`);

try {
  // Get file info before deletion
  const fileInfo = await drive.files.get({
    fileId: args.fileId,
    fields: 'name,mimeType',
  });

  const fileName = fileInfo.data.name;
  const isFolder = fileInfo.data.mimeType === 'application/vnd.google-apps.folder';

  if (args.skipTrash) {
    await drive.files.delete({
      fileId: args.fileId,
    });
    return `Permanently deleted ${isFolder ? 'folder' : 'file'} "${fileName}".`;
  } else {
    await drive.files.update({
      fileId: args.fileId,
      requestBody: {
        trashed: true,
      },
    });
    return `Moved ${isFolder ? 'folder' : 'file'} "${fileName}" to trash. It can be restored from the trash.`;
  }
} catch (error: any) {
  log.error(`Error deleting file: ${error.message || error}`);
  if (error.code === 404) throw new UserError("File not found. Check the file ID.");
  if (error.code === 403) throw new UserError("Permission denied. Make sure you have delete access to this file.");
  throw new UserError(`Failed to delete file: ${error.message || 'Unknown error'}`);
}
}
});

// --- Document Creation Tools ---

server.addTool({
name: 'createDocument',
description: 'Creates a new Google Document.',
parameters: z.object({
  title: z.string().min(1).describe('Title for the new document.'),
  parentFolderId: z.string().optional().describe('ID of folder where document should be created. If not provided, creates in Drive root.'),
  initialContent: z.string().optional().describe('Initial text content to add to the document.'),
}),
execute: async (args, { log }) => {
const drive = await getDriveClient();
log.info(`Creating new document "${args.title}"`);

try {
  const documentMetadata: drive_v3.Schema$File = {
    name: args.title,
    mimeType: 'application/vnd.google-apps.document',
  };

  if (args.parentFolderId) {
    documentMetadata.parents = [args.parentFolderId];
  }

  const response = await drive.files.create({
    requestBody: documentMetadata,
    fields: 'id,name,webViewLink',
  });

  const document = response.data;
  let result = `Successfully created document "${document.name}" (ID: ${document.id})\nView Link: ${document.webViewLink}`;

  // Add initial content if provided
  if (args.initialContent) {
    try {
      const docs = await getDocsClient();
      await docs.documents.batchUpdate({
        documentId: document.id!,
        requestBody: {
          requests: [{
            insertText: {
              location: { index: 1 },
              text: args.initialContent,
            },
          }],
        },
      });
      result += `\n\nInitial content added to document.`;
    } catch (contentError: any) {
      log.warn(`Document created but failed to add initial content: ${contentError.message}`);
      result += `\n\nDocument created but failed to add initial content. You can add content manually.`;
    }
  }

  return result;
} catch (error: any) {
  log.error(`Error creating document: ${error.message || error}`);
  if (error.code === 404) throw new UserError("Parent folder not found. Check the folder ID.");
  if (error.code === 403) throw new UserError("Permission denied. Make sure you have write access to the destination folder.");
  throw new UserError(`Failed to create document: ${error.message || 'Unknown error'}`);
}
}
});

server.addTool({
name: 'createFromTemplate',
description: 'Creates a new Google Document from an existing document template.',
parameters: z.object({
  templateId: z.string().describe('ID of the template document to copy from.'),
  newTitle: z.string().min(1).describe('Title for the new document.'),
  parentFolderId: z.string().optional().describe('ID of folder where document should be created. If not provided, creates in Drive root.'),
  replacements: z.record(z.string()).optional().describe('Key-value pairs for text replacements in the template (e.g., {"{{NAME}}": "John Doe", "{{DATE}}": "2024-01-01"}).'),
}),
execute: async (args, { log }) => {
const drive = await getDriveClient();
log.info(`Creating document from template ${args.templateId} with title "${args.newTitle}"`);

try {
  // First copy the template
  const copyMetadata: drive_v3.Schema$File = {
    name: args.newTitle,
  };

  if (args.parentFolderId) {
    copyMetadata.parents = [args.parentFolderId];
  }

  const response = await drive.files.copy({
    fileId: args.templateId,
    requestBody: copyMetadata,
    fields: 'id,name,webViewLink',
  });

  const document = response.data;
  let result = `Successfully created document "${document.name}" from template (ID: ${document.id})\nView Link: ${document.webViewLink}`;

  // Apply text replacements if provided
  if (args.replacements && Object.keys(args.replacements).length > 0) {
    try {
      const docs = await getDocsClient();
      const requests: docs_v1.Schema$Request[] = [];

      // Create replace requests for each replacement
      for (const [searchText, replaceText] of Object.entries(args.replacements)) {
        requests.push({
          replaceAllText: {
            containsText: {
              text: searchText,
              matchCase: false,
            },
            replaceText: replaceText,
          },
        });
      }

      if (requests.length > 0) {
        await docs.documents.batchUpdate({
          documentId: document.id!,
          requestBody: { requests },
        });

        const replacementCount = Object.keys(args.replacements).length;
        result += `\n\nApplied ${replacementCount} text replacement${replacementCount !== 1 ? 's' : ''} to the document.`;
      }
    } catch (replacementError: any) {
      log.warn(`Document created but failed to apply replacements: ${replacementError.message}`);
      result += `\n\nDocument created but failed to apply text replacements. You can make changes manually.`;
    }
  }

  return result;
} catch (error: any) {
  log.error(`Error creating document from template: ${error.message || error}`);
  if (error.code === 404) throw new UserError("Template document or parent folder not found. Check the IDs.");
  if (error.code === 403) throw new UserError("Permission denied. Make sure you have read access to the template and write access to the destination folder.");
  throw new UserError(`Failed to create document from template: ${error.message || 'Unknown error'}`);
}
}
});

// --- Server Startup ---
async function startServer() {
try {
await initializeGoogleClient(); // Authorize BEFORE starting listeners
console.error("Starting Ultimate Google Docs MCP server...");

      // Using stdio as before
      const configToUse = {
          transportType: "stdio" as const,
      };

      // Start the server with proper error handling
      server.start(configToUse);
      console.error(`MCP Server running using ${configToUse.transportType}. Awaiting client connection...`);

      // Log that error handling has been enabled
      console.error('Process-level error handling configured to prevent crashes from timeout errors.');

} catch(startError: any) {
console.error("FATAL: Server failed to start:", startError.message || startError);
process.exit(1);
}
}

startServer(); // Removed .catch here, let errors propagate if startup fails critically

```
Page 1/2FirstPrevNextLast